我真正需要做的是将浮点数导出到C而没有精度损失.
我在python中这样做了:
import math
import struct
x = math.sqrt(2)
print struct.unpack('ii', struct.pack('d', x))
# prints (1719614413, 1073127582)
Run Code Online (Sandbox Code Playgroud)
在CI中试试这个:
#include <math.h>
#include <stdio.h>
int main(void)
{
unsigned long long x[2] = {1719614413, 1073127582};
long long lx;
double xf;
lx = (x[0] << 32) | x[1];
xf = (double)lx;
printf("%lf\n", xf);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但在CI获得:
7385687666638364672.000000而不是sqrt(2).
我错过了什么?
谢谢.
Python代码似乎有效.问题出在C代码中:你已经long long填好了,但是你将整数值直接转换为浮点数,而不是将字节重新解释为a double.如果你在它上面抛出一些指针/寻址,它可以工作:
jkugelman$ cat float.c
#include <stdio.h>
int main(void)
{
unsigned long x[2] = {1719614413, 1073127582};
double d = *(double *) x;
printf("%f\n", d);
return 0;
}
jkugelman$ gcc -o float float.c
jkugelman$ ./float
1.414214
Run Code Online (Sandbox Code Playgroud)
另请注意,double(和for float)的格式说明符%f不是%lf.%lf是为了long double.
| 归档时间: |
|
| 查看次数: |
6379 次 |
| 最近记录: |