为什么增加小数位数不会影响欧氏距离的计算时间?

问题描述

我正在尝试对 KMeans 程序进行微基准测试。我目前专注于欧几里得距离。我认为(由于下面的平方根)增加每个坐标(x,y)的小数位数会导致计算时间增加

以下是我计算欧几里得距离的方法

Math.sqrt((x - otherPoint.x) * (x - otherPoint.x) + (y - otherPoint.y) * (y - otherPoint.y))

以下是我的微基准测试结果:

Benchmark                 (noOfFloatingPoints)  (noOfPoints)  Mode  Cnt       score         Error  Units
TheBenchmark.toyBenchmark                    16          5000  avgt    5  251214.457 ±   40224.490  ns/op
TheBenchmark.toyBenchmark                     8          5000  avgt    5  319809.483 ±  560434.712  ns/op
TheBenchmark.toyBenchmark                     2          5000  avgt    5  477652.450 ± 1068570.972  ns/op

如您所见,分数实际上随着小数位数的减少而增加!我已经在 5000 点上尝试过这个,但是无论我使用多少点还是多少点都一样。

为什么会这样?我认为浮点数越多,需要的计算就越多,特别是由于平方根。

为了增加小数位数,我创建了这个函数

public static double generaterandomToDecimalPlace(Random rnd,int lowerBound,int upperBound,int decimalPlaces) {
            final double dbl = (rnd.nextDouble() * (upperBound - lowerBound)) + lowerBound;
            return roundAvoid(dbl,decimalPlaces);
        }

    public static double roundAvoid(double value,int places) {
        double scale = Math.pow(10,places);
        return Math.round(value * scale) / scale;
    }

我在一定范围(-100 到 100)和特定小数点之间随机生成点:

    @Param({"16","8","2"})
    public int noOfFloatingPoints;

解决方法

类型 double 是二进制、固定长度的数据类型。无论您的数字有多少个小数点,它始终使用 64 位来表示一个值。此外,由于它是用二进制编码的,它甚至不使用小数点。它使用基数为 2 的算法来使用浮点数。