lldb 和 C 代码为 pow() 给出了不同的结果

lldb and C code give different results for pow()

我有一个变量,Npart,它是一个 int 并初始化为 64。下面是我的代码 (test.c):

#include <math.h>
#include <stdio.h>

int Npart, N;

int main(){

Npart = 64;

N = (int) (pow(Npart/1., (1.0/3.0)));
printf("%d %d\n",Npart, N);

return 0;
};

打印出 64 3,可能是由于数值精度问题。我编译如下:

gcc -g3 test.c -o test.x

如果我尝试使用 lldb 进行调试,我尝试计算该值并在命令提示符中打印它,会发生以下情况:

$ lldb ./test.x
(lldb) target create "./test.x"
Current executable set to './test.x' (x86_64).
(lldb) breakpoint set --file test.c --line 1
Breakpoint 1: where = test.x`main + 44 at test.c:8, address = 0x0000000100000f0c
(lldb) r
Process 20532 launched: './test.x' (x86_64)
Process 20532 stopped
* thread #1: tid = 0x5279e0, 0x0000000100000f0c test.x`main + 44 at test.c:8, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000100000f0c test.x`main + 44 at test.c:8
   5    
   6    int main(){
   7    
-> 8    Npart = 64;
   9    
   10   N = (int) (pow(Npart/1., (1.0/3.0)));
   11   printf("%d %d\n",Npart, N);
(lldb) n
Process 20532 stopped
* thread #1: tid = 0x5279e0, 0x0000000100000f12 test.x`main + 50 at test.c:10, queue = 'com.apple.main-thread', stop reason = step over
frame #0: 0x0000000100000f12 test.x`main + 50 at test.c:10
   7    
   8    Npart = 64;
   9    
-> 10   N = (int) (pow(Npart/1., (1.0/3.0)));
   11   printf("%d %d\n",Npart, N);
   12   
   13   return 0;
(lldb) n
Process 20532 stopped
* thread #1: tid = 0x5279e0, 0x0000000100000f4a test.x`main + 106 at test.c:11, queue = 'com.apple.main-thread', stop reason = step over
    frame #0: 0x0000000100000f4a test.x`main + 106 at test.c:11
   8    Npart = 64;
   9    
   10   N = (int) (pow(Npart/1., (1.0/3.0)));
-> 11   printf("%d %d\n",Npart, N);
   12   
   13   return 0;
   14   };
(lldb) print Npart
(int) [=12=] = 64
(lldb) print (int)(pow(Npart/1.,(1.0/3.0)))
warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
(int)  = 0
(lldb) print (int)(pow(64,1.0/3.0))
(int)  = 0

为什么 lldb 给出不同的结果?

编辑: 澄清了问题并提供了一个最小的可验证示例。

你的代码计算了 64 的立方根,应该是 4。

C 代码通过 flooring 将 return 值转换为整数。 pow 通常以某种泰勒多项式或类似的形式实现——这在数值上往往不准确。您计算机上的结果似乎略小于 4.0,当转换为 int 时会 truncated - 解决方案是首先使用 lround相反:

N = lround(pow(Npart/1., (1.0/3.0)));

至于lldb,关键是正文:

error: 'pow' has unknown return type; cast the call to its declared return type

即它 不知道函数的 return 类型 - 因此是原型。 pow 声明为

double pow(double x, double y);

但是由于 lldb 关于 return 类型的唯一提示是您提供的转换,lldb 认为原型是

int pow(int x, double y);

这将导致未定义的行为 - 实际上,lldb 认为 return 值应该是来自 EAX 寄存器的 int,因此 0 是打印,但实际 return 值在某个浮动 point/SIMD 寄存器中。同样,由于参数的类型也是未知的,因此您不能传入 int

因此我猜你会在调试器中使用

获得正确的值
print (double)(pow(64.0, 1.0/3.0))