在C#和JavaScript中的IEEE 754浮点运算舍入错误 [英] IEEE 754 floating point arithmetic rounding error in c# and javascript

查看:365
本文介绍了在C#和JavaScript中的IEEE 754浮点运算舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是读了一本关于javascript的书。作者在IEEE 754标准中提到了一个浮点算术舍入误差。例如,加0.1和0.2会得到0.30000000000000004而不是0.3。

所以(0.1 + 0.2)== 0.3 返回false。

我也转载这个错误在C#中。

因此这些是我的问题是:

这个错误发生的频率如何?
什么是在C#和JavaScript的最佳做法解决方法?
其他语言有哪些相同的错误?

解决方案

这不是语言错误。这在IEEE 754中不是错误的。这是二进制浮点数的期望和使用的错误。一旦你理解了什么二进制浮点数真的是,这是非常合理的。



在C#中的最佳实践是使用 System.Decimal (又名十进制),它是一个十进制浮点类型,无论何时处理数量自然用十进制表示 - 通常是货币值。



请参阅我在.NET上的文章二进制浮点数十进制浮点数获取更多信息。


I just read a book about javascript. The author mentioned a floating point arithmetic rounding error in the IEEE 754 standard.

For example adding 0.1 and 0.2 yields 0.30000000000000004 instead of 0.3.

so (0.1 + 0.2) == 0.3 returns false.

I also reproduced this error in c#.

So these are my question is:

How often this error occurs? What is the best practice workaround in c# and javascript? Which other languages have the same error?

解决方案

It's not an error in the language. It's not an error in IEEE 754. It's an error in the expectation and usage of binary floating point numbers. Once you understand what binary floating point numbers really are, it makes perfect sense.

The best practice in C# is to use System.Decimal (aka decimal) which is a decimal floating point type, whenever you're dealing with quantities which are naturally expressed in decimal - typically currency values.

See my articles on .NET binary floating point and decimal floating point for more information.

这篇关于在C#和JavaScript中的IEEE 754浮点运算舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆