PowerShell计算错误

标签 powershell math

我偶然发现了这个简单的数学方程,但 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. The Double data type is faster and requires less memory, but it is subject to rounding errors. The Decimal data type retains complete accuracy to 28 decimal places.

Floating-point (Single and Double) numbers have larger ranges than Decimal numbers but can be subject to rounding errors. Floating-point types support fewer significant digits than Decimal but can represent values of greater magnitude.

关于PowerShell计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593706/

相关文章:

xml - Powershell 无法设置 xmlelement 的内部文本

powershell - 了解哈希表数组的唯一性

powershell - 从一个导入 csv 将多个用户添加到多个组

我可以将 NULL 传递给 modf/modff 吗?

python - Cython 中神奇的 libc.math.abs

algorithm - 找到 a^b^c^... mod m

powershell - 使用 Powershell v2.0 通过 Google API 删除 Gmail 电子邮件

winforms - 使用 PowerShell 访问 WebView2 中的 cookie

java - 我们如何计算小于 1 的数字的对数值...?使用java

algorithm - DFA - 设计一个 DFA 接受超过 {0,1} 的所有字符串,最多包含两个 0 0's and three 11' 作为子字符串