除双打时精度C#损失 [英] C# loss of precision when dividing doubles
问题描述
我知道这已经再次讨论了一次,但我似乎无法得到,甚至双打的一步师的最简单的例子,导致在C#中预计,未四舍五入的结果 - 所以我想知道是否也许有一些如编译器标记或别的东西,怪我没有想到的。考虑这个例子:
双V1 = 0.7;
双V2 = 0.025;
双重结果= V1 / V2;
在我的最后一行后突破并检查它在VS调试器,结果的价值是27.999999999999996。我知道,我可以通过改变解决它十进制,但是那是不可能在周边项目的情况。这难道不奇怪,两个低精度双打这样不能分割到28正确的价值?是唯一的解决方案,真正Math.Round结果呢?
这难道不奇怪两个低精度双打这样不能分割到28正确的价值?
块引用>
没有,真的没有。无论是0.7还是0.025可以在
精确表示双
键入。涉及的精确值:0.6999999999999999555910790149937383830547332763671875
0.025000000000000001387778780781445675529539585113525390625
的现在的你感到惊讶,该司没有给予确切28?垃圾进,垃圾出...
就像你说的,正确的结果,代表的小数的数字究竟是使用
小数
。如果你的程序的其它部分使用了错误的类型,只是意味着你需要工作,这是更高:得到错误的答案,或者改变整个项目的造价成本I know this has been discussed time and time again, but I can't seem to get even the most simple example of a one-step division of doubles to result in the expected, unrounded outcome in C# - so I'm wondering if perhaps there's i.e. some compiler flag or something else strange I'm not thinking of. Consider this example:
double v1 = 0.7; double v2 = 0.025; double result = v1 / v2;
When I break after the last line and examine it in the VS debugger, the value of "result" is 27.999999999999996. I'm aware that I can resolve it by changing to "decimal," but that's not possible in the case of the surrounding program. Is it not strange that two low-precision doubles like this can't divide to the correct value of 28? Is the only solution really to Math.Round the result?
解决方案Is it not strange that two low-precision doubles like this can't divide to the correct value of 28?
No, not really. Neither 0.7 nor 0.025 can be exactly represented in the
double
type. The exact values involved are:0.6999999999999999555910790149937383830547332763671875 0.025000000000000001387778780781445675529539585113525390625
Now are you surprised that the division doesn't give exactly 28? Garbage in, garbage out...
As you say, the right result to represent decimal numbers exactly is to use
decimal
. If the rest of your program is using the wrong type, that just means you need to work out which is higher: the cost of getting the wrong answer, or the cost of changing the whole program.这篇关于除双打时精度C#损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!