两个双精度值相加时出现算术错误
可能的重复:
浮点不准确示例
Java 中的双精度算术和相等
我在尝试调试排序时发现了这个问题检查两个值是否相等的例程。获取这些值只需对两个双精度变量进行一些加法:0.31 + 0.27。
当排序将这两个对象的总和与其他一些对象(其总和也等于 0.58)进行比较时,它告诉我比较不相等。查看第一个对象的总和,我看到它列出的是 0.58000000000000007。想知道这是否与我的代码有关,我创建了一个简单的控制台应用程序来测试它:
static void Main(string[] args)
{
double val1 = .31;
double val2 = .27;
Console.WriteLine("Value 1: " + val1);
Console.WriteLine("Value 2: " + val2);
double added = val1 + val2;
if (!added.Equals(.58))
Console.WriteLine("Added value is not .58!");
else
Console.WriteLine("Added value is .58");
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
在我的机器上运行它,它又是 0.58000000000000007。我让一位同事做了同样的事情并得出了相同的输出。
以前有人遇到过这个吗?我们都运行 64 位 Windows 7,这是用 C# 完成的 - 我还没有在其他场景中测试过它。
Possible Duplicate:
Floating point inaccuracy examples
double arithmetic and equality in Java
I caught this issue while trying to debug a sorting routine that checked if two values were equal. Getting the values was simply doing some addition on two double variables: 0.31 + 0.27.
When the sort compared the sum of those two against the some of another objects, whose sum also equaled 0.58, it told me the comparison was not equal. Looking at the first object's sum, I saw it was listing it as 0.58000000000000007. Wondering if it was something with my code, I created a simple console app to test it out:
static void Main(string[] args)
{
double val1 = .31;
double val2 = .27;
Console.WriteLine("Value 1: " + val1);
Console.WriteLine("Value 2: " + val2);
double added = val1 + val2;
if (!added.Equals(.58))
Console.WriteLine("Added value is not .58!");
else
Console.WriteLine("Added value is .58");
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
Ran it on my machine, and it was 0.58000000000000007 again. I had a co-worker do the same and came up with the same output.
Has anyone come across this before? We are both running 64-bit Windows 7, and this was done in C# - I haven't tested it out in other scenarios.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与
.31
和.27
没有精确的二进制表示有关。我发现这篇文章很有用。This has to do with the fact that
.31
and.27
do not have exact binary representations. I found this article useful.这是浮点精度的问题。您可以做的就是将该值乘以 100(两个房屋的十进制精度),然后将其转换为 int 或 long。所以比较运行得很完美。
如果想深入研究这个主题可以搜索Stallings的计算机体系结构书籍。链接:http://williamstallings.com/
This is a problem with floating point precision. What you could do is multiply the value by 100 (decmais accuracy of two houses) and make a cast to int or long. So the comparison run perfectly.
If you want to study in depth the subject of the search for Stallings book of computer architecture. link: http://williamstallings.com/
您需要定义一个epsilon或一个最大可接受的误差。
You need to define an epsilon or a greatest-acceptable-error.