I am trying to calculate arkus sin() without math library. It works, however produces different results on different platforms.
Windows and Mac (correct): 5.2359877560e-001 Linux: 5.1532736669e-01
Where is problem?
double my_asin(double k)
{
double x = k;
double a = 1;
double s = x;
const double hodnota = 0.00000000001f;
double s1 = 0;
double d = x;
double e = 1.0;
double y;
y = x * x;
while(my_abs(s1 - s) >= hodnota) {
s1 = s;
d = d * y;
e = e * ((a * a) / ((++a) * (++a)) );
s = s + (d * e);
}
return s;
}
Instruction e = e * ((a * a) / ((++a) * (++a)) ); can produce different results because of undefined behavior
You need to change your code this way:
e *= a * a / ((a + 1) * (a + 2));
a += 2;
This line has undefined effect.
e = e * ((a * a) / ((++a) * (++a)) );
You need to move one, and ideally both the incrmements to a different line. eg:
e = e * ((a * a) / ((a+2) * (a+1)) );
a+=2
Though you will need to play with the replacement line until it actually does what you hope.
Btw, this code could easily vary across version of compilers, not just compiler brands and OS's.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With