双减双精度问题

发布于 2024-08-31 00:33:16 字数 229 浏览 4 评论 0原文

我在 .NET 中遇到了 double 的精度问题,我认为这仅适用于浮点数,但现在我发现 double 是浮点数。

double test = 278.97 - 90.46;
Debug.WriteLine(test) //188.51000000000005

//correct answer is 188.51

处理这个问题的正确方法是什么?圆形的?去掉不需要的小数位?

I have come across a precision issue with double in .NET I thought this only applied to floats but now I see that double is a float.

double test = 278.97 - 90.46;
Debug.WriteLine(test) //188.51000000000005

//correct answer is 188.51

What is the correct way to handle this? Round? Lop off the unneeded decimal places?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽清梦 2024-09-07 00:33:16

使用十进制数据类型。 “小数值类型适用于需要大量有效整数和小数位并且没有舍入错误的财务计算。”

Use the decimal data type. "The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors."

鸠书 2024-09-07 00:33:16

这种情况在许多语言中都会发生,源于我们通常无法在数字硬件中精确存储双精度数或浮点数这一事实。有关双精度数、浮点数和所有其他浮点值通常如何存储的详细说明,请查看维基百科上描述的各种 IEEE 规范。例如: http://en.wikipedia.org/wiki/Double_ precision

当然还有其他格式,例如定点格式。但大多数语言中都存在这种不精确性,这也是为什么在条件语句中使用双精度数时经常需要使用 epsilon 测试而不是相等测试(即,abs(x - y) <= 0.0001 而不是 x == y)。

如何处理这种不精确性取决于您,并且取决于您的应用程序。

This happens in many languages and stems from the fact that we cannot usually store doubles or floats precisely in digital hardware. For a detailed explanation of how doubles, floats, and all other floating point values are often stored, look at the various IEEE specs described on wikipedia. For example: http://en.wikipedia.org/wiki/Double_precision

Of course there are other formats, such as fixed-point format. But this imprecision is in most languages, and why you often need to use epsilon tests instead of equality tests when using doubles in conditionals (i.e. abs(x - y) <= 0.0001 instead of x == y).

How you deal with this imprecision is up to you, and depends on your application.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文