浮子上的运算会失去精度并更改符号

问题描述

| 我有一个特殊的问题。我的任务是在工作中重构一些旧的C代码,但遇到了问题。 我有三个浮点数组,分别为VIL,ZET和GZ3D。 VIL中的值是使用以下代码生成的:
for(k=1;k<sommet[i];k++)
{
    if(ZET[k][i]>0)
    {
        Z=pow(10.0,ZET[k][i]/10.0);
        VIL[i]=VIL[i]+0.00344*(GZ3D[k][i]-GZ3D[k-1][i])*(float)pow(Z,(4.0/7.0))/1000.0;
    }
}
我复制了包含计算的函数,并运行了它。但是现在,当我比较旧代码(即corect)创建的结果和我的结果时,我得到了:
VIL is not equal between the two files at the index [10748]
Values \"old:new\" :0.079468:-0.086186
VIL is not equal between the two files at the index [10749]
Values \"old:new\" :0.073242:-0.085514
VIL is not equal between the two files at the index [10750]
Values \"old:new\" :0.070435:-0.083805
VIL is not equal between the two files at the index [10751]
Values \"old:new\" :0.067200:-0.081059
VIL is not equal between the two files at the index [10752]
Values \"old:new\" :0.063843:-0.077580
VIL is not equal between the two files at the index [10753]
Values \"old:new\" :0.056824:-0.072087
VIL is not equal between the two files at the index [10754]
Values \"old:new\" :0.054077:-0.068363
所以我得到的结果是负数,总是相差约10%。 有人知道是什么原因造成的吗?     

解决方法

如上所述,使用双重计算并为操作设置手动优先级
VIL[i]=VIL[i]+ ((0.00344*(GZ3D[k][i]-GZ3D[k-1][i])) * ((float)pow(Z,(4.0/7.0))) /1000.0);
您应尽可能避免降低精度的操作:两个非常大或非常小的值相乘,一个操作数较大而第二个操作数较小的加法或减法等等。     ,尝试对转换和变量类型使用double而不是float。双精度大小是8个字节,而浮点数是4。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...