Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ optimization options affect the value of sin function

Tags:

c++

c

I have a problem with "sin" function of libc.

#include <cmath>
#include <stdio.h>

int main(int argc, char **argv)
{
    double tt = 6.28318530717958620000; // 2 * M_PI
    double yy = ::sin(tt);

    printf("%.32f\n", yy);

    return 0;
}

When compile the above code using "g++" without any optimization option, it would output "-0.00000000000000024492127076447545". But if with "-O3" option, it would output "-0.00000000000000024492935982947064".

Why doesn't it return "-0.00000000000000024492935982947064" without "-O3"? Thanks in advance.

like image 356
Shen Weizheng Avatar asked Feb 12 '12 14:02

Shen Weizheng


1 Answers

Because with "-O3" the compiler precomputes sin(2*pi) at compile time, with one algorithm. Without "-O3" this is computed at runtime, with other algorithm.

This may be because compiler itself was built with some math library, which differ from your math library.

Update

The only entity, giving the result "-0.00000000000000024492127076447545" is 32-bit version of libstdc++. 64-bit version of the same library as well as gcc itself produce "-0.00000000000000024492935982947064".

So upgrading to newer version will not help. Also I tried various options, proposed here: neither -ffloat-store, nor -fno-builtin do not make any difference, as well as long double and sinl.

32-bit libstdc++ uses 387 floating point instructions, while gcc apparently uses SSE instructions. Here is the difference. Probably, the only way to make them consistent is to rebuild gcc from sources, directing it to use only 387 instructions internally.

like image 199
Evgeny Kluev Avatar answered Nov 01 '22 01:11

Evgeny Kluev