Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange cbrt() result on linux in C

Tags:

Why these two return value of the cbrt() function are different ?

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

int main() {
    double nb = 56623104;
    double v1 = cbrt(nb);
    printf("v1 -> %.15f\n",v1);

    double v2 = cbrt((double) 56623104);
    printf("v2 -> %.15f\n",v2);
}

Compilation :

gcc toto.c -o toto -lm && ./toto

Result :

v1 -> 384.000000000000057
v2 -> 384.000000000000000

like image 749
Benjish Avatar asked Feb 08 '17 21:02

Benjish


1 Answers

Congratulations, this is a compiler bug. The compiler is optimizing your code by evaluating one of the cbrt calls ahead of time, unfortunately, the compiler's version of cbrt is different from your version in libm. You will also notice that passing -O2 causes the v2 result to be "wrong" as well (even though it's right, mathematically).

I verified that the bug exists on my system

cc (Debian 6.3.0-5) 6.3.0 20170124

This bug should be reported to the compiler developers (https://gcc.gnu.org/bugs/), but it's a good idea to search the bug repository first.

like image 142
Dietrich Epp Avatar answered Sep 25 '22 10:09

Dietrich Epp