Using float and double for calculation, giving different results

I am working on a project where we calculate the prices of items with 8 decimal places. But sometimes the calculation results are different.

I tried several samples but got different calculation results:

    public static void main(String[] args) {
        double value1 =  0.999939f * 0.987792f;
        double value2 =  0.999939 * 0.987792;
        double value3 =  (double)0.999939f * 0.987792f;     
        System.out.println("value 1 : "+ value1);
        System.out.println("value 2: "+ value2);
        System.out.println("value 3 : "+ value3);
    }

      

Outputs:

value 1 : 0.9877317547798157
value 2 : 0.9877317446880001
value 3 : 0.9877317839126931

      

These are three different results.

I am embarrassed. Can anyone please clarify for me what's going on here?
Thank.

I went through some already answered, but I just want some ways that I could only count with floats and doubleles. otherwise I have to change many places. It will be painful.

+3


source to share


2 answers


Because of the way floats and decimal numbers are represented, casts can lead to different results.

For: double value1 = 0.999939f * 0.987792f

you are multiplying two floats and then casting them to double. The resulting floating point representation is a double conversion.

For: double value2 = 0.999939 * 0.987792;

you multiply two doubles and store them at double. This is a time when there is no casting, so the view never changes (i.e. there is no potential data loss from changing the data view).



For: double value3 = (double)0.999939f * 0.987792f;

you are multiplying the double, which is called from the float, times the float. Because of the way Java math works, this second float is probably also cast to a double, so now you are multiplying the two doubles that once floated calling the third set of views.

Since float and double have different predicates, each will get a different result. For more information on floating point arithmetic see here .

+3


source


When you write a number with the "f" character it is taken as float

, that is, it is encoded in 32 bits, whereas without it it double

is encoded in 64 bits.

The more bits, the more accurately the decimal numbers will be represented. This does not affect a number with multiple decimal places, but it does matter in your case.



Finally, use only double

variables in your code.

+1


source







All Articles