我偶然发现了这个简单的数学方程,但 PowerShell 出错了。
PS 99.804-99.258
0.546000000000006
PS 10.804-10.258
0.546000000000001
这让我很好奇,我尝试了一些不同的计算器,大多数计算器都正确并返回
0.546
还有:
PS 1.804-1.258
0.546
也是正确的。 但我发现其他计算器也返回错误的结果:
0.54600000000001
0.545999999999999999
0.5460000000000065
为什么会发生这种情况以及如何在 PowerShell 中获得正确的结果?
最佳答案
这是因为示例中使用的默认类型是 System.Double
,
99.804.GetType()
>>>>IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Double System.ValueType
在您的特定情况下,您想要使用的是 System.Decimal
哪个更精确,
[decimal]99.804-[decimal]99.258
>>>>0.546
或者,
99.804d-99.258d
>>>>0.546
更多信息
我觉得有必要澄清我所说的“更精确”的含义。基本上,重要的是要了解 double 类型的范围比decimal 类型大得多。但是,更大的范围并不意味着更准确。
实际上,System.Decimal
最初是为了解决小数点可能困惑的货币/金钱问题而创建的。 它的精确性取决于它对 System.Double
使用以 10 为底的数学而不是以 2 为底的数学。显然,后者计算效率更高,但准确性较差。
这可以在 MSDN documentation 中进行验证其中指出,
You can use
Decimal
variables for money values. The advantage is the precision of the values. TheDouble
data type is faster and requires less memory, but it is subject to rounding errors. TheDecimal
data type retains complete accuracy to 28 decimal places.Floating-point (
Single
andDouble
) numbers have larger ranges thanDecimal
numbers but can be subject to rounding errors. Floating-point types support fewer significant digits thanDecimal
but can represent values of greater magnitude.
关于PowerShell计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593706/