c – C中的浮点运算出错
作者:互联网
请让我知道以下C函数之间的区别.
static int mandel(float c_re, float c_im, int count) {
float z_re = c_re, z_im = c_im;
int i;
for (i = 0; i < count; ++i) {
if (z_re * z_re + z_im * z_im > 4.f)
break;
float new_re = z_re*z_re - z_im*z_im;
float new_im = 2.f * z_re * z_im;
z_re = c_re + new_re;
z_im = c_im + new_im;
}
return i;
}
以下
static int mandel(float c_re, float c_im, int count) {
float z_re = c_re, z_im = c_im;
int i;
for (i = 0; i < count; ++i) {
if (z_re * z_re + z_im * z_im > 4.f)
break;
float new_im = 2.f * z_re * z_im;
z_re = c_re + z_re*z_re - z_im*z_im;//I have combined the statements here and removed float new_re
z_im = c_im + new_im;
}
return i;
}
请参阅我对代码更改的注释.函数为某些输入提供不同的值.由于两个陈述相结合,浮动是否会被误解?
解决方法:
在数学中,这两个陈述是等价的.但是在计算机硬件中它们可能不是.
您可能会出错,因为初始结果(new_re)已四舍五入,然后添加到c_re.
正如尼克拉斯所说:
intermediate values are stored with higher precision
因此,当存储到new_re时,new_re的结果可能会丢失一些浮点,但如果将中间值添加到c_re,则较小的c_re值与new_re计算的较低有效值组合可能会导致最终结果.
标签:c-3,c,floating-point,floating-accuracy 来源: https://codeday.me/bug/20190901/1785162.html