更快地执行Math.round? [英] Faster implementation of Math.round?

查看:76
本文介绍了更快地执行Math.round?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否存在任何缺陷,似乎是java.lang.Math.round的较快(正确)版本?

Are there any drawbacks to this code, which appears to be a faster (and correct) version of java.lang.Math.round?

public static long round(double d) {

    if (d > 0) {
        return (long) (d + 0.5d);
    } else {
        return (long) (d - 0.5d);
    }
}

它利用了以下事实:在Java中,将长整数舍入为零.

It takes advantage of the fact that, in Java, truncating to long rounds in to zero.

推荐答案

有一些

There are some special cases which the built in method handles, which your code does not handle. From the documentation:

  • 如果参数为NaN,则结果为0.
  • 如果参数为负无穷大或任何小于或等于Integer.MIN_VALUE的值,则结果等于Integer.MIN_VALUE的值.
  • 如果参数为正无穷大或大于或等于 等于Integer.MAX_VALUE的值,结果等于Integer.MAX_VALUE的值.
  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

这篇关于更快地执行Math.round?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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