简体   繁体   中英

Float vs double Math Java

Is there a precision difference between the following (assuming the value of a and b can be represented without loss of precision in a float).

With floats:

float a;
float b;
double result = 1 + a*b;

With doubles:

double a;
double b;
double result = 1 + a*b;

Simple example:

float a = 16777217;  // Largest int exactly representable in a float.
float b = 16777217;
System.out.println((double)(1 + a*b));

double c = 16777217;
double d = 16777217;
System.out.println(1 + c*d);

Output ( Ideone ):

2.81474976710656E14
2.8147501026509E14

So yes, there is a loss of precision using float .

There is a loss of precision in

float a;
float b;
double result = 1 + a*b;
  • the float representation.
  • the product of a and b which will also be a float . Note: a * b is a float
  • the addition on 1 could result in a loss of precision.

To should that a * b can lose more precision

for (int i = 1; i < 100; i += 2) {
    float a = i;
    float b = 1.0f / i;
    if ((double) a * b != a * b && a * b != 1)
        System.out.println(i + " " + (double) a * b + " " + a * b);
}

prints

41 0.999999962747097 0.99999994
47 0.9999999683350325 0.99999994
55 0.9999999683350325 0.99999994
61 0.9999999441206455 0.99999994
83 0.999999962747097 0.99999994
97 0.999999969266355 0.99999994

note: it could also happen recover precision lost and get the right answer after b has lost precision

for (int i = 1; i < 20; i += 2) {
    float a = i;
    float b = 1.0f / i;
    if (b != 1.0 / i && a * b == 1)
        System.out.println(i + " " + (double) a * b + " " + a * b);
}

prints

3 1.0000000298023224 1.0
5 1.0000000149011612 1.0
7 1.0000000447034836 1.0
9 1.0000000074505806 1.0
11 1.0000000298023224 1.0
13 1.000000037252903 1.0
15 1.0000000521540642 1.0
17 1.0000000037252903 1.0
19 1.0000000074505806 1.0

There can be a loss of precision difference in a*b part when you evaluating it as floats and doubles. So yes, with some values, 2nd one will be more accurate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM