加法的十进制顺序会影响结果 [英] Decimal order of addition affects results

查看:72
本文介绍了加法的十进制顺序会影响结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个系统正在使用小数进行大量计算,偶尔会累加相同的数字,但返回不同的结果,+/-0.000000000000000000000000001

I have a system that is performing lots of calculations using decimals, occasionally it will add up the same numbers, but return different results, +/- 0.000000000000000000000000001

这是一个简短的示例:

decimal a = 2.016879990455473621256359079m;
decimal b = 0.8401819425625631128956517177m;
decimal c = 0.4507062854741283043456903406m;
decimal d = 6.7922317815078349615022988627m;

decimal result1 = a + b + c + d;
decimal result2 = a + d + c + b;

Console.WriteLine((result1 == result2) ? "Same" : "DIFFERENT");
Console.WriteLine(result1);
Console.WriteLine(result2);

输出:

DIFFERENT
10.100000000000000000000000000
10.100000000000000000000000001

差异是如此之小,以至于没有实际效果,但是以前有人见过这样的东西吗?我希望当将相同的数字相加时,您总是会得到相同的结果.

The differences are so small that there is no practical effect, but has anyone seen something like this before? I expected that when adding up the same numbers you would always get the same results.

推荐答案

数值分析致力于研究这种影响以及如何避免这种影响.

The entire field of Numerical analysis is devoted to studying these kind of effects and how to avoid them.

要在对浮点数列表求和时产生最佳结果,请先从最小到最大对列表进行排序,然后按该顺序将它们相加.

To produce the best result when summing a list of floating point numbers, first sort the list from smallest to largest, and add them up in that order.

这篇关于加法的十进制顺序会影响结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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