Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does integer division by zero 1/0 give error but floating point 1/0.0 returns "Inf"?

Tags:

java

int

double

I'm just curious about this:

When evaluating 1/0 in Java, the following exception occurs:

Exception in thread "main" java.lang.ArithmeticException: / by zero at Foo.main(Foo.java:3)

But 1/0.0 is evaluated to Infinity.

public class Foo {     public static void main (String[] args) {         System.out.println(1/0.0);     } } 

Why does this happen?

like image 995
Fábio Perez Avatar asked Mar 13 '11 19:03

Fábio Perez


People also ask

What happens when an integer is divided by a float?

If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.

What is the outcome when a floating point number is divided by zero?

Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.

Can a floating point number be divided by an integer?

The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division. The result of integer division is always an integer.

What happens when you divide a floating-point value by 0 in Java?

Java will not throw an exception if you divide by float zero. It will detect a run-time error only if you divide by integer zero not double zero. If you divide by 0.0, the result will be INFINITY.


2 Answers

That's because integers don't have values for +/-Inf, NaN, and don't allow division by 0, while floats do have those special values.

like image 119
ninjalj Avatar answered Oct 07 '22 06:10

ninjalj


1/0 is a division of two ints, and throws an exception because you can't divide by integer zero. However, 0.0 is a literal of type double, and Java will use a floating-point division. The IEEE floating-point specification has special values for dividing by zero (among other thing), one of these is double.Infinity.

If you're interested in details, the floating-point spec (which is often cryptic) has a page at Wikipedia: http://en.wikipedia.org/wiki/IEEE_754-2008, and its full text can be also read online: http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933.

like image 27
Kristóf Marussy Avatar answered Oct 07 '22 08:10

Kristóf Marussy