问题
Code:
class Main {
public static void main (String[] args) {
System.out.print("float: ");
System.out.println(1.35f-0.00026f);
System.out.print("double: ");
System.out.println(1.35-0.00026);
}
}
Output:
float: 1.34974
double: 1.3497400000000002
??? float got the right answer, but double is adding extra stuff from no where, Why??
Isn't double supposed to be more precise than float?
回答1:
A float is 4 bytes wide, whereas a double is 8 bytes wide.
Check What Every Computer Scientist Should Know About Floating-Point Arithmetic
Surely the double has more precision so it has slightly less rounding error.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
On a side note:-
I would suggest if you want the exact decimal values then use java.math.BigDecimal
回答2:
If you know something about the rules for converting double values to strings, which are specified by the documentation for Double.toString [Java-API], you know that the program prints the shortest decimal fraction sufficient to distinguish the double value from its nearest neighbor, with at least one digit before and after the decimal point.
Check Joshua Bloch's Java Puzzlers: Traps, Pitfalls, and Corner Cases - Puzzle 2: Time for a Change. He explains this question in that chapter.
回答3:
The reason of this is the mechanism of numbers with floating point calculation. Also when java tries to print a float value, it truncates trailing zeroes. And, you know, double type uses 8 bytes and float uses 4. So the double precision is bigger.
So, when java calculates your float value, it gets something like 1.3497400 and truncates it before output. And when java calculates your double value, it gets more digits and so you get such result.
Try to execute this simple example for better understanding:
public class Test {
public static void main( String[] args ) {
float sum = 0;
for (int i = 1; i <= 10; i++) {
sum += 0.1;
}
System.out.println( sum );
}
}
public class Test {
public static void main( String[] args ) {
double sum = 0;
for (int i = 1; i <= 10; i++) {
sum += 0.1;
}
System.out.println( sum );
}
}
来源:https://stackoverflow.com/questions/19444081/java-float-is-more-precise-than-double