Simple equation fails unit test
I have method that takes 2 integers as arguments and returns:
public int method(int a, int b){
return Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10)
}
I have created unit test, which passes for values 1400 and 1500 (expected value is 43), however it fails for 1459 and 1500. The expected output is 18, however my method returns 17. I believe this might have something to do with rounding, however i cannot see any obvious error. There should not be any problems with rounding 17.7(6) to 18.
EDIT开发者_运维技巧:
the real function was slighty different (I did not have Math.abs(a-b) but instead I had defined "diff" variable as a result of this. I could promise you guys that i declared it as double diff; - I have no idea why it become int diff :) SOLVED thanks :)
Math.abs
and Math.min
both return int
s when passed int
s as arguments, so your code is doing integer division instead of the double division that you are expecting. If you replace the 3
and the 10
with 3.0
and 10.0
, your code should work as you expect.
It's because it's performing integer division. With a = 1459
, b = 1500
:
Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10)
Math.round(Math.abs(41)/3 - (1459-1500)/10)
Math.round(41/3 - (-41)/10)
Math.round(13 - (-4))
Math.round(17) // note that round will always get an integer as input
17
The easy fix is to force it to perform floating point division instead by using a float as one of the arguments:
Math.round((Math.abs(a-b)/3.0) - (Math.min(a,b)-1500)/10.0)
Expecting a double when using integer division has to be the oldest gotcha in the book. ;)
Your round doesn't do anything as your integer divisions produce integer result.
The expected outcome is 17.
|a-b| = 41
|a-b|/3 = 13
min(a,b) = 1459
min(a,b)-1500 = -41
(min(a,b)-1500)/10 = -4
13-(-4) = 17
I suspect you do not want to have integer division. Therefore you must replace 3
and 10
by 3.0
and 10.0
.
You must remember to take into account the fact that when an integer is divided by another integer in Java, the result is an integer, not a float (any remainder is dropped). For example 6/4 == 1
, not 1.5
.
method(1459, 1500)
Math.round((Math.abs(1459-1500)/3) - (Math.min(1459,1500)-1500)/10);
Math.round((41/3) - (1459-1500)/10);
Math.round(13 - (-41)/10); //41/3 == 13, not 13.6666
Math.round(13 - -4); //-41/10 == -4, not -4.1
Math.round(17);
17
精彩评论