physicist
physicist

Reputation: 904

Weird floating point exception

In the code snippet below I get a floating point exception during run time. I believe the exception happens at the line where division by r is being done. When I comment that line out I get no error.

Also very very strangely when I compile in gcc with the "-g" flag (to try to debug) OR if I insert some "cout statement" immediately after the "if statement" then I don't get any floating point exception at runtime.

I have been staring at my screen on this code for hours, maybe I am making some stupid mistake.. please help!

    double prev;
    for(int i=0;i<320;i++)
    for(int j=0;j<320;j++) 
    {
        double x = -8 + i*0.05;
        double y = -8 + j*0.05;
        r= sqrt(x*x+y*y);

        double kappa = atanh(  (2*r)  / ( 2 +  r*r)  );                     

        if( fabs(r) > 1e-7 )
        { 
            prev= ( x*sinh(kappa) )/r; 
        }
         else
        {
            prev=0;         

        }
        /* more stuff */ 
    }

UPDATE: So I was able to fix the problem by adding 1e-15 to the denominator on the contentious line ..

prev= ( x*sinh(kappa) )/(r+1e-15);

I am still not sure why the if condition gives true .. for if(fabs(r)>1e-7) when r =0;

Upvotes: 0

Views: 397

Answers (1)

kpie
kpie

Reputation: 11120

Sqrt of a negitive number? try

r= sqrt(fabs(x*x+y*y)); 

on line 7 of your snippet.

Upvotes: 0

Related Questions