Thread overview
int, double and divide by zero
Nov 18, 2005
Newbie
Nov 18, 2005
xs0
Nov 18, 2005
Don Clugston
November 18, 2005
Hi,

Coming from Delphi, I'm currently learning D.

Sorry if the same question has already been posted before.

void main()
{
	int a,b,r;

	a = 2;
	b = 0;
	try
	{
		r = a / b;
		writefln ( r );
	}
	catch ( Exception e)
	{
		writefln ( e );
	}

}

This program does not work, integer divide by zero exception... But :

void main()
{
	double a,b,r;

	a = 2;
	b = 0;
	try
	{
		r = a / b;
		writefln ( r );
	}
	catch ( Exception e)
	{
		writefln ( e );
	}

}

r = infinite, the exception is not catched when a b and r are double.

Is it a normal behaviour on D programming language ??

Thanks.
November 18, 2005
Newbie wrote:
> Hi,
> 
> Coming from Delphi, I'm currently learning D.
> 
> Sorry if the same question has already been posted before.
> 
> [snip int div w/0]
> 
> This program does not work, integer divide by zero exception... But :
> 
> [snip double div w/0]
> 
> r = infinite, the exception is not catched when a b and r are double.
> 
> Is it a normal behaviour on D programming language ??

AFAIK, it's a normal behavior in many languages - doubles can represent infinity and integers cannot, so they are handled differently, I guess..


xs0
November 18, 2005
Newbie wrote:
> Hi,
> 
> This program does not work, integer divide by zero exception... But :
> 
> void main()
> {
>     double a,b,r;
> 
>     a = 2;
>     b = 0;
>     try
>     {
>         r = a / b;
>         writefln ( r );
>     }
>     catch ( Exception e)
>     {
>         writefln ( e );
>     }
> 
> }
> 
> r = infinite, the exception is not catched when a b and r are double.
> 
> Is it a normal behaviour on D programming language ??

Yes. IEEE real numbers include + and - infinity.
This turns out to be very useful -- it means that you often don't have to worry about division by zero.

Suppose you wrote:

double t = tanh(a/b);

The hyperbolic tangent of x has the property that it approaches +1.0 as x approaches +infinity (and is -1.0 at -infinity).
The code above gives the correct value for t, even when b is zero!
Otherwise, you'd have to write,

double t;
if (b==0 && a>0) {
   t = 1.0;
} else if (b==0 && a<0) {
   t = -1.0;
} else {
   t = tanh(a/b);
}

IEEE floating-point arithmetic is one of the seven wonders of the computing world. And yet most programmers don't know how it works.
They still live in fear of division by zero.

Have no fear! You only need to worry if your final result ends up with a NAN (not-a-number, a special value meaning the results are garbage because you used an uninitialized variable, or did a 0/0, 0 * infinity, or infinity/infinity somewhere). But if your final result is +-infinity, it's a correct result.