Nel seguente programma è possibile vedere che ciascun valore leggermente inferiore a .5
viene arrotondato per difetto, ad eccezione di 0.5
.Perché Math.round (0.49999999999999994) restituisce 1?
for (int i = 10; i >= 0; i--) {
long l = Double.doubleToLongBits(i + 0.5);
double x;
do {
x = Double.longBitsToDouble(l);
System.out.println(x + " rounded is " + Math.round(x));
l--;
} while (Math.round(x) > i);
}
stampe
10.5 rounded is 11
10.499999999999998 rounded is 10
9.5 rounded is 10
9.499999999999998 rounded is 9
8.5 rounded is 9
8.499999999999998 rounded is 8
7.5 rounded is 8
7.499999999999999 rounded is 7
6.5 rounded is 7
6.499999999999999 rounded is 6
5.5 rounded is 6
5.499999999999999 rounded is 5
4.5 rounded is 5
4.499999999999999 rounded is 4
3.5 rounded is 4
3.4999999999999996 rounded is 3
2.5 rounded is 3
2.4999999999999996 rounded is 2
1.5 rounded is 2
1.4999999999999998 rounded is 1
0.5 rounded is 1
0.49999999999999994 rounded is 1
0.4999999999999999 rounded is 0
sto usando Java 6 Update 31.
Nel mio caso la risposta è 0 e non 1 e l'ultima riga non viene stampata mentre interrompe il loop lì. Qui è la mia uscita ...... 8,499999999999998 arrotondato è 8 7.5 arrotondato è 8 7,499999999999999 arrotondato è 7 6.5 arrotondato è 7 6,499999999999999 arrotondata è 6 5.5 arrotondata è 6 5,499999999999999 arrotondato è 5 4,5 arrotondata è 5 4.499999999999999 arrotondato è 4 3.5 arrotondato è 4 3.4999999999999996 arrotondato è 3 2,5 arrotondato è 3 2.4999999999999996 sferici sono 2 1,5 arrotondato è 2 1,4999999999999998 arrotondate è 1 0,5 arrotondato è 1 0,49999999999999994 arrotondato è 0 –
su Java 1.7.0 funziona bene http://i.imgur.com/hZeqx.png – Coffee
@Adel: Vedi il mio commento su [risposta di Oli] (http://stackoverflow.com/a/9903075/157247), sembra che Java 6 implementa questo (e [documenti che lo fa] (http://docs.oracle.com/javase /6/docs/api/java/lang/Math.html#round(double))) in un modo che può causare un'ulteriore perdita di precisione aggiungendo '0.5' al numero e quindi usando' floor'; Java 7 [non lo documenta più in questo modo] (http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round (double)) (presumibilmente/si spera perché lo hanno risolto). –