是否有一种优化的、高效的方法可以将 double 舍入到最接近给定的二分数幂的倍数的精确值?
换句话说,将 .44
舍入到最接近的 1/16(换句话说,可以表示为 n/16
的值,其中 n
是一个整数)将是 .4375
。注意:这是相关的,因为两个分数的幂可以在没有舍入误差的情况下存储,例如
public class PowerOfTwo {
public static void main(String... args) {
double inexact = .44;
double exact = .4375;
System.out.println(inexact + ": " + Long.toBinaryString(Double.doubleToLongBits(inexact)));
System.out.println(exact + ": " + Long.toBinaryString(Double.doubleToLongBits(exact)));
}
}
输出:
0.44: 11111111011100001010001111010111000010100011110101110000101001
0.4375: 11111111011100000000000000000000000000000000000000000000000000
最佳答案
如果你想选择二的幂,最简单的方法是乘以例如16,舍入到最接近的整数,然后除以 16。请注意,如果结果是正常数,则除以 2 的幂是准确的。它可能会导致次正规数的舍入误差。
下面是一个使用这种技术的示例程序:
public class Test {
public static void main(String[] args) {
System.out.println(roundToPowerOfTwo(0.44, 2));
System.out.println(roundToPowerOfTwo(0.44, 3));
System.out.println(roundToPowerOfTwo(0.44, 4));
System.out.println(roundToPowerOfTwo(0.44, 5));
System.out.println(roundToPowerOfTwo(0.44, 6));
System.out.println(roundToPowerOfTwo(0.44, 7));
System.out.println(roundToPowerOfTwo(0.44, 8));
}
public static double roundToPowerOfTwo(double in, int power) {
double multiplier = 1 << power;
return Math.rint(in * multiplier) / multiplier;
}
}
输出:
0.5
0.5
0.4375
0.4375
0.4375
0.4375
0.44140625
关于java - 两个分数的幂的最近倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238149/