是的,我想我真的是在做梦。我在 AIX 机器上编译并运行了以下代码:
AIX 3 5
PowerPC_POWER5 processor type
IBM XL C/C++ for AIX, V10.1
Version: 10.01.0000.0003
#include <stdio.h>
#include <math.h>
#define RADIAN(x) ((x) * acos(0.0) / 90.0)
double nearest_distance(double radius,double lon1, double lat1, double lon2, double lat2){
double rlat1=RADIAN(lat1);
double rlat2=RADIAN(lat2);
double rlon1=lon1;
double rlon2=lon2;
double a=0,b=0,c=0;
a = sin(rlat1)*sin(rlat2)+ cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1);
printf("%lf\n",a);
if (a > 1) {
printf("aaaaaaaaaaaaaaaa\n");
}
b = acos(a);
c = radius * b;
return radius*(acos(sin(rlat1)*sin(rlat2)+
cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1)));
}
int main(int argc, char** argv) {
nearest_distance(6367.47,10,64,10,64);
return 0;
}
现在,计算后“a”的值报告为“1”。而且,在这台 AIX 机器上,当我输入“if”时,看起来 1 > 1 为真!我认为“1”的 acos 返回 NanQ,因为 1 大于 1。请问这怎么可能?我不知道该怎么想了!
该代码在其他架构上运行得很好,其中“a”实际上取的是我认为的 1 的值,而 acos(a) 是 0。
最佳答案
If you do a comparison where result and expctedResult are float types:
if (result == expectedResult)
Then it is unlikely that the comparison will be true. If the comparison is true then it is probably unstable – tiny changes in the input values, compiler, or CPU may change the result and make the comparison be false.
与 epsilon 比较 – 绝对误差
if (fabs(result - expectedResult) < 0.00001)
来自Comparing floating point numbers
<小时/>What Every Computer Scientist Should Know About Floating-Point Arithmetic
关于c - 什么时候a>a为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2743718/