Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results in OS Windows and Linux

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;

}
like image 575
user3071818 Avatar asked Feb 03 '26 07:02

user3071818


2 Answers

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;
like image 176
vzhilin Avatar answered Feb 04 '26 20:02

vzhilin


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.

like image 32
RichardPlunkett Avatar answered Feb 04 '26 20:02

RichardPlunkett