blog icon indicating copy to clipboard operation
blog copied to clipboard

java中Math.abs(x) < 1e-7是什么意思?

Open TFdream opened this issue 4 years ago • 0 comments

最近在刷leetcode 69. x 的平方根 的时候发现 官方给出的 方法三:牛顿迭代 java代码如下:

class Solution {
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }

        double C = x, x0 = x;
        while (true) {
            double xi = 0.5 * (x0 + C / x0);
            if (Math.abs(x0 - xi) < 1e-7) {
                break;
            }
            x0 = xi;
        }
        return (int) x0;
    }
}

Math.abs(x0 - xi) < 1e-7 第一次看见这种写法有点懵,Google了一番之后才明白 Math.abs(x) < 1e-7 其实相当于x == 0

1e-7(也就是0.0000001)叫做epslon,用来抵消浮点运算中因为误差造成的相等无法判断的情况。它通常是一个非常小的数字(具体多小要看你的运算误差)

在一开始学习c语言的时候,我们就知道计算机在存储数据的时候是使用二进制,而二进制是无法准确存储double数据的。至于是为什么,不要问我,因为我也是新手,而java语言的底层也是c、c++,所以也是同理。

比如说因为精度误差,用十进制举例,我们要算1/3+1/3+1/3 == 1(从数学上说,肯定相等),但是因为精度问题,等号左边算出来是0.3333333+0.3333333+0.3333333 = 0.9999999,存在了误差,右边是1.0000000,那么如果直接用 == ,返回false,我们希望它被视作相等。那么就要两数相减取绝对值小于epslon的办法。

TFdream avatar Sep 10 '21 08:09 TFdream