| |
| Posted by Don Clugston in reply to Newbie | PermalinkReply |
|
Don Clugston
Posted in reply to Newbie
| 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.
|