gpt4 book ai didi

PowerShell计算错误

转载 作者:行者123 更新时间:2023-12-03 00:33:40 28 4
gpt4 key购买 nike

我偶然发现了这个简单的数学方程,但 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com