Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# variable declaration changes output

Daniel .J.Hyslop
Ranch Hand
Posts: 55
in the program below I have initialised two variables with int values and decrement the variable f by one each repetition f eventually becomes 0 which creates a ArithmeticException and I get the desired result for the exercise the code is below

the resultant output is
120/5 is 24
120/4 is 30
120/3 is 40
120/2 is 60
120/1 is 120
cannot devide by zero ---which is what I expectd

I changed the variable f to a double :-

and got this
120/5.0 is 24.0 etc.....
120/1.0 is 120.0
120/0.0 is infinity

Would someone be kind enough to tell me what causes the difference in output when a varialbles initialiser is changed , please

M. Gagnon
Ranch Hand
Posts: 68
Originally posted by daniel hyslop:

120/0.0 is infinity

Would someone be kind enough to tell me what causes the difference in output when a varialbles initialiser is changed , please

According to Horstman and Cornell in "Core Java", that is the normal behavior for types float and double:

". . . the result of dividing a positive number by 0 is positive infinity."

I think it's probably because floating point numbers always have a limited precision.

Philip Heller
author
Ranch Hand
Posts: 119
You only get ArithmeticException when you divide an integer by integer zero.

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by M. Gagnon:
I think it's probably because floating point numbers always have a limited precision.

It's actually part of the IEEE Standard 754 for floating point numbers.

http://stevehollasch.com/cgindex/coding/ieeefloat.html

Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations. Operations with infinite values are well defined in IEEE floating point.