Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding division by zero

 
palla sridhar
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers!
Please look at the code below.
This prints "Infinity" compiled and executed.
Q1. How does it print "Infinity" ?
But when i code like this
and compile,execute,it gives "Arithmetic Exception,
Q2. Why so?

Please help??
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first case you current salary is a double initialised with a promoted int, dividing a double by int 0 promotes 0 to double so you are diving two doubles , dividing by zero when in double land ;-) gives Double.Infinity.

Second case you are diving two integers the result of which will be promoted to a double but before that happens the division of two integers occurs ... the result in integer land of division by 0 is an ArithmeticException :-)
 
Arvind Mahendra
Ranch Hand
Posts: 1162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by palla sridhar:
Hi Ranchers!
Please look at the code below.
This prints "Infinity" compiled and executed.
Q1. How does it print "Infinity" ?
But when i code like this
and compile,execute,it gives "Arithmetic Exception,
Q2. Why so?

Please help??


I think this had something to do with the fact that floats/ doubles unlike integeres had 3 parts. : the sign, the mantissa(part of the floating point that contains the significant digits) and the exponent. Internally because we now have an extra part ie:the exponent part you have extra space to represent certain special things within the cpu when you omit an exponent in your representation. So it can use that space to give out values like "infinite". ints dont have that extra space so they choke when faced with a divide by zero and have to throw an exception.
note; i think this may also have to change from CPU to CPU. maybe somone with a mac computer could confirm because its not just divide by zero that can represent "infinities" but other values as well. it may be that some give Nan(when a result of a calculation doesn't really exists like Math.sqrt(-1) for example
[ October 21, 2007: Message edited by: Chunnard Singh II ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic