Author Topic:   Math class
Vivian, Song
greenhorn
posted March 17, 2000 04:05 PM         
Could anybody tell me why is this?

Math.round(5.5); //6
Math.round(-5.5); //-5

Should they be either "6, -6" or "5,-5"?
Thanks!
Vivian

maha anna
bartender
posted March 17, 2000 05:38 PM             
Vivian,
Remembember the number ordering
-------------------------------
-inf .-6.0 -5.0 -4.0 -3.0 -2.0 -1.0.... -0.0 +0.0 1.0 2.0 .. 4.0 5.0 6.0.....+inf

- Math.round(float f) returns an 'int'
- Math.round(double d) returns 'long'
- In the above scale if you take any 2 numbers the number which is nearer to -inf is always lesser than the other number.
(1 exception is -0.0 == +0.0 is true, But min(-0.0,+0.0) will give ans as -0.0)
For +ve numbers
- If the input arg to the round(..) method contains a fractional part, and if the fractional part is >= .5 then the nearest int to the Right in the above shown scale is returned.
else
The same number without the fraction is returned as int/long
For -ve numbers
- If the input arg to the round(..) method contains a fractional part, and if the fractional part is <= .5 then the nearest int to the Right in the above shown scale is returned.
else
The same number without the fraction is returned as int/long

- So applying the above rules
Math.round(5.5); // fractional part .5 is >= .5 . so the for 5.5,next number on the above scale on the Right Hand Side is 6. Since Math.round(double d) returns a long and the returned val is long 6.

Math.round(-5.5); // fractional part .5 is <= .5 . so for -5.5, the next integer on the above scale on the Right Hand Side is -5.0. Since Math.round(double d) returns a long the returned val is long -5.

- If there is no fractional part / the fractional part is .0 (ex. 10.0) then the same no is returned as int/long

This is the concept. Now you are on your own for testing
regds
maha anna

[This message has been edited by maha anna (edited March 17, 2000).]

Howard Stern
ranch hand
posted March 17, 2000 05:53 PM             
In case of a round(float d)

The result is rounded to an integer by adding 1/2 to the argument, taking the floor of the result, and casting the result to type int.

In other words, the result is equal to the value of the expression:


(int)Math.floor(a + 0.5f)
In case of a round(double d)
The result is rounded to an integer by adding 1/2 to the argument, taking the floor of the result, and casting the result to type int.
(int)Math.floor(a + 0.5d)

Thus:
round(3.2) does the following :

3.2+.5 = 3.7 //adds 1/2 to the argument
floor(3.7)= 3//returns the floor value

round(-3.6) does the following

-3.6+.5 = -3.1
floor(-3.1)= -4


you can yourself find out for the rest of the argument values. Hope this explains.

|