浮点数与双精度数学 Java

Float vs double Math Java

以下是否存在精度差异(假设a和b的值可以在不损失精度的情况下用float表示)

有花车:

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

有双打:

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

当您将 a*b 部分评估为浮点数和双精度数时,可能会丢失精度差异。所以是的,有了一些值,第二个会更准确。

简单示例:

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);

输出(Ideone):

2.81474976710656E14
2.8147501026509E14

所以是的,使用 float.

会导致精度损失

中存在精度损失
float a;
float b;
double result = 1 + a*b;
  • float 表示。
  • ab 的乘积也将是 float。注意:a * bfloat
  • 1 的加法可能会导致精度损失。

应该 a * b 可以失去更多的精度

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);
}

打印

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

注意:在b失去精度

后,也可能发生恢复精度丢失并得到正确答案的情况
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);
}

打印

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