将浮点值舍入到java中最接近的整数的最有效方法是什么? [英] What is the most efficient way to round a float value to the nearest integer in java?

查看:344
本文介绍了将浮点值舍入到java中最接近的整数的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多关于SO与舍入浮点值有关的讨论,但考虑到效率方面没有可靠的Q& A.所以这是:

I've seen a lot of discussion on SO related to rounding float values, but no solid Q&A considering the efficiency aspect. So here it is:

将浮点值舍入到最接近的整数的最有效(但正确)方法是什么?

What is the most efficient (but correct) way to round a float value to the nearest integer?

(int) (mFloat + 0.5);

Math.round(mFloat);

FloatMath.floor(mFloat + 0.5);

还是别的什么?

我喜欢我希望使用标准java库中可用的东西,而不是我必须导入的一些外部库。

Preferably I would like to use something available in standard java libraries, not some external library that I have to import.

推荐答案

public class Main {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            measurementIteration();
        }
    }

    public static void measurementIteration() {
        long s, t1 = 0, t2 = 0;
        float mFloat = 3.3f;
        int f, n1 = 0, n2 = 0;
        for (int i = 0; i < 1E4; i++) {
            switch ((int) (Math.random() * 2)) {
            case 0:
                n1 += 1E4;
                s = System.currentTimeMillis();
                for (int k = 0; k < 1E4; k++)
                    f = (int) (mFloat + 0.5);
                t1 += System.currentTimeMillis() - s;
                break;
            case 1:
                n2 += 1E4;
                s = System.currentTimeMillis();
                for (int k = 0; k < 1E4; k++)
                    f = Math.round(mFloat);
                t2 += System.currentTimeMillis() - s;
                break;
            }
        }
        System.out.println(String.format("(int) (mFloat + 0.5): n1 = %d    -> %.3fms/1000", n1, t1 * 1000.0 / n1));
        System.out.println(String.format("Math.round(mFloat)  : n2 = %d    -> %.3fms/1000", n2, t2 * 1000.0 / n2));
    }
}

Java SE6上的输出:

Output on Java SE6:

(int) (mFloat + 0.5): n1 = 500410000    -> 0.003ms/1000
Math.round(mFloat)  : n2 = 499590000    -> 0.022ms/1000

Java SE7上的输出(感谢 alex 结果):

Output on Java SE7 (thanks to alex for the results):

(int) (mFloat + 0.5): n1 = 50120000 -> 0,002ms/1000
Math.round(mFloat) : n2 = 49880000 -> 0,002ms/1000

正如您所看到的, Math.round 从SE6到SE7。我认为在SE7中不再存在显着差异,你应该选择对你来说更具可读性的东西。

As you can see, there was a huge performance improvement on Math.round from SE6 to SE7. I think in SE7 there is no significant difference anymore and you should choose whatever seems more readable to you.

这篇关于将浮点值舍入到java中最接近的整数的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆