Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this crash? Aren't I dividing by zero here?

I'm getting the slope of a line bounded by two points

float slopeXY(CGPoint p1, CGPoint p2)
{
    return ((p2.y - p1.y) / (p2.x - p1.x));
}

If I give it a zero-sized line,

CGPoint p1 = CGPointMake(0, 10);
CGPoint p2 = CGPointMake(0, 10);

float sxy = slopeXY(p1, p2);

I don't get a divide by zero error.

like image 694
willc2 Avatar asked Sep 19 '09 18:09

willc2


2 Answers

With the default floating-point environment on OS X, floating-point division by zero does not cause a trap or exception. 0.0/0.0 will instead return a NaN and raise the invalid floating-point status flag in the fpscr. Dividing a non-zero value by 0.0 will return an infinity and raise the divide-by-zero flag.

You can check for these conditions, if you need to, using the isnan( ) and isinf( ) functions defined in math.h

like image 163
Stephen Canon Avatar answered Oct 03 '22 00:10

Stephen Canon


Divide by zero error only happens for integer division. For float, normally you get infinity, unless the dividend is zero.

like image 40
RichN Avatar answered Oct 03 '22 02:10

RichN