Using float and double for calculation, giving different results
This question already has an answer here:
Because of how floats and decimals are represented, the casts could be causing different results.
For: double value1 = 0.999939f * 0.987792f
you are multiplying two floats and then casting it to a double. The resulting float representation is the one being converted to a double.
For: double value2 = 0.999939 * 0.987792;
you are multiply two doubles and saving it in a double. This is time there is no casting so the representation never changes (ie. no potential data loss from change in data representation).
For: double value3 = (double)0.999939f * 0.987792f;
you are multiplying a double that is casted from a float, times a float. Because of how the Java math works, that second float is probably also being casted to a double, so now you are multiplying two doubles that were once floats causing a third set of representations.
Because float and doubles have different precisions each of these will get a different result. For more info about floating point arithmetic, see here.
When you write a number with the "f" character, it is taken as float
, meaning it is encoded with 32bits, whereas without it, it is a double
, encoded with 64bits.
The more bits, the more accurately you will represent decimal numbers. This does not make a difference for number with few decimals, but in your case it is significant.
In conclusion, use exclusively double
variables in your code.
上一篇: 一轮浮动值