wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Math class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Math class" Watch "Math class" New topic
Author

Math class

Harsha Vardhan Madiraju
Greenhorn

Joined: Dec 19, 2003
Posts: 24
hi all,
Can anyone explain me how the below comparison is true or returns true
Math . round ( Integer . MIN_VALUE - 6.5f ) == Integer . MIN_VALUE
Thanx in advance
Donny Nadolny
Ranch Hand

Joined: Mar 05, 2003
Posts: 32
It has to do with what data a float can hold - it can hold 1.4E-45 to 3.4E38, which means that there are certain values it cannot hold which are in between those values.
For example, Math.round(99.499999f) = 100. You and I can see that when you round that number it should be 100, but a float can't hold the exact number 99.499999 and the closest number that it can see is 99.5 something. Hope this helps (I don't believe the SCJP expects you to know the rounded (integer or long) value of any float or double value). Hope this helps.


- Donny Nadolny<br />The pen is mightier than the sword, and considerably easier to write with.
Sriram Chintapalli
Ranch Hand

Joined: Dec 16, 2003
Posts: 59
Hi Harsha,
Math . round ( Integer . MIN_VALUE - 6.5f ) == Integer . MIN_VALUE
returns true because an integer can hold a minimum number -2 power of 31. Here we are rounding a value that actually should return Integer.MIN_Value-6 but an integer cannot hold such a small value so it rounds it to its minimum value Integer.MIN_VALUE. This behavior is symmetric and when we round a value that is more than Integer.MAX_Value it automatically rounds it to Integer.MAX_VALUE (ie) System.out.println(Math.round(Integer.MAX_VALUE + 1.5f)==Integer.MAX_VALUE); is true.
And yes sire in case you were wondering this is the same with Long also
System.out.println(Math.round(Long.MAX_VALUE + 1.5)==Long.MAX_VALUE);
returns true.
Hope this helps.
sriram
Donny Nadolny
Ranch Hand

Joined: Mar 05, 2003
Posts: 32
Here we are rounding a value that actually should return Integer.MIN_Value-6 but an integer cannot hold such a small value so it rounds it to its minimum value Integer.MIN_VALUE

I don't believe that it's because an integer can't hold a small value - see the output from the following code:

The output will be a very large number (2.19 billion approx) because Java's numbers are signed - when you try to go too low, they loop around to be positive. I believe the answer to the question is the response I gave previously .
CH Lee
Ranch Hand

Joined: Nov 24, 2003
Posts: 42
Hi guys,
This is a very interesting topic. I did some testing with all the listed code and found this on API documentation.

Hope this helps us understand it better.
Cheers.
[ February 10, 2004: Message edited by: CH Lee ]
 
jQuery in Action, 2nd edition
 
subject: Math class