Search code examples
mathlanguage-agnosticdivide-by-zero

Integer divide by Zero and Float (Real no.) divide by Zero


If I run following line of code, I get DIVIDE BY ZERO error

1. System.out.println(5/0);

which is the expected behavior.

Now I run the below line of code

2. System.out.println(5/0F);

here there is no DIVIDE BY ZERO error, rather it shows INFINITY

In the first line I am dividing two integers and in the second two real numbers.

Why does dividing by zero for integers gives DIVIDE BY ZERO error while in the case of real numbers it gives INFINITY

I am sure it is not specific to any programming language.


Solution

  • (EDIT: The question has been changed a bit - it specifically referred to Java at one point.)

    The integer types in Java don't have representations of infinity, "not a number" values etc - whereas IEEE-754 floating point types such as float and double do. It's as simple as that, really. It's not really a "real" vs "integer" difference - for example, BigDecimal represents real numbers too, but it doesn't have a representation of infinity either.

    EDIT: Just to be clear, this is language/platform specific, in that you could create your own language/platform which worked differently. However, the underlying CPUs typically work the same way - so you'll find that many, many languages behave this way.

    EDIT: In terms of motivation, bear in mind that for the infinity case in particular, there are ways of getting to infinity without dividing by zero - such as dividing by a very, very small floating point number. In the case of integers, there's obviously nothing between zero and one.

    Also bear in mind that the cases in which integers (or decimal floating point types) are used typically don't need to concept of infinity, or "not a number" results - whereas in scientific applications (where float/double are more typically useful), "infinity" (or at least, "a number which is too large to sensibly represent") is still a potentially valid result.