我在一个大型C编程项目中遇到了一个数值问题。 (这是统计研究,而不是课堂作业)。一步涉及计算sqrt(x ^ 2 + y) - x,我需要为正,但有时我得到sqrt(x ^ 2 + y) - x<即使x> 0也是0 0和y> 0.示例:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
float x = 1210.9088134,
y = 0.0062529947;
printf("x =\t\t\t%70.50f\n", x);
printf("y =\t\t\t%70.50f\n", y);
printf("x*x =\t\t\t%70.50f\n", x*x);
printf("x*x + y =\t\t%70.50f\n", x*x + y);
printf("sqrt(x*x + y) =\t\t%70.50f\n", sqrt(x*x + y));
printf("sqrt(x*x + y) - x =\t%70.50f\n", sqrt(x*x + y) - x);
}
我的输出:
x = 1210.90881347656250000000000000000000000000000000000000
y = 0.00625299476087093353271484375000000000000000000000
x*x = 1466300.12500000000000000000000000000000000000000000000000
x*x + y = 1466300.12500000000000000000000000000000000000000000000000
sqrt(x*x + y) = 1210.90880127282912326336372643709182739257812500000000
sqrt(x*x + y) - x = -0.00001220373337673663627356290817260742187500000000
此输出充满了奇怪的行为。亮点:
为什么1-3会发生?
我应该提一下:我在带有gcc版本的64位Mac OX 10.9.4机器上运行了这个例子:
$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
和带有gcc版本的64位CentOS服务器:
$ gcc --version
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
此外,编译在任何一台机器上都没有返回任何错误或警告:
$ gcc -lm -Wall -pedantic -ansi test.c -o test