Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atan2f precision on xcode

Tags:

c++

math

I have this very simple code:

#include <cstdio>
#include <cmath>

int main(int argc, const char * argv[])
{
    printf("%2.21f", atan2f(0.f, -1.f));

    return 0;
}

With next output on Intel CPUs:

Visual Studio 2010: 3.141592741012573200000
GCC 4.8.1         : 3.141592741012573242188
Xcode 5           : 3.141592502593994140625

After reading Appple manual pages for atan2f, I expect the printed value to be near 3.14159265359, as they say they will return +pi for special values like the one I'm using now. As you can see the difference is quite big from the value returned on Xcode and expected value.

Is this a know issue? If yes, is there any workaround to solve this?

like image 481
Mircea Ispas Avatar asked Aug 09 '26 04:08

Mircea Ispas


2 Answers

A single-precision floating point number has only about 7 digits of decimal precision. Your test value of 3.14159265359 has 12. If you want better precision, use double or long double and atan2 or atan2l to match.

Likely the reason you're getting "better" results from VS and GCC is that the compiler is noticing your function has constant arguments and is precalculating the result at higher-than-single precision. Check the generated code for proof.

like image 69
Carl Norum Avatar answered Aug 10 '26 18:08

Carl Norum


The knee-jerk workaround is to use atan2. Casting that down to float gave me 3.141592741012573242188 just like your GCC 4.8.1 test.

I would assume atan2f gives an answer not quite as precise as a float could hold because it arrives at its answer by some means that means that estimating the output precision is a smarter way to go.

like image 24
Tommy Avatar answered Aug 10 '26 17:08

Tommy