float 变量的精度为 6,这(如果我理解正确的话)意味着计算机实际存储的数字与您想要的实际数字之间的差异将小于 10^-6
这意味着a和b都有小于10^-6的误差
The 10-6 figure is a rough measure of the relative accuracy when representing arbitrary constants as floats. Not all numbers will be represented with an absolute error of 10-6. The number 8765432.1, for instance, can be expected to be represented approximately to the unit. If you are at least a little bit lucky, you will get 8765432 when representing it as a float
. On the other hand, 1E-15f
can be expected to be represented with an absolute error of at most about 10-21.
所以在计算机内部 a 实际上可能是 1.229100000012123 而 b 可能是 3.9900000191919
不,抱歉,它的工作方式并不是您写下整个数字并为可能的错误添加六个零。可以通过计算 6 个零来估计误差leading数字,而不是从最后一位数字开始。在这里,您可能期望 1.22910012123 或 3.990000191919。
(实际上,您将准确地得到 1.2290999889373779296875 和 3.9900000095367431640625。不要忘记,表示误差可以是负数,也可以是正数,就像第一个数字一样。)
现在假设您有以下代码[...]
我的问题是
will c
最终结果的精度误差是否也小于10^-6?
No. The total absolute error will be the sum of all the representation errors for a
and b
for each of the thousand times you used them, plus the errors of the 2000 additions you did. That's 4000 different sources of error! Many of them will be identical, some of them will happen to compensate each other, but the end result will probably not be to 10-6 relative accuracy, more like 10-5 relative accuracy (suggestion done without counting).