问题:
给定任意双下限、双上限和双增量,确定给定输入双精度范围的最快方法是什么?如果您不关心内存使用、使用预计算等,您能比使用双除法的明显方法做得更好吗?注意:这个类的重复使用不太可能完全相同的双精度值,换句话说,将结果缓存在 a 中Map<Double, Double>
可能无济于事。
直截了当的回答:
public class RangeFinder {
private double lowerBound;
private double higherBound;
private double increment;
public RangeFinder(double lowerBound, double higherBound, double increment) {
if(increment < 0) throw new IllegalArgumentException("Increment cannot be negative!");
this.lowerBound = lowerBound;
this.higherBound = higherBound;
this.increment = increment;
}
public int getRange(double number) {
if (number < lowerBound) return 0;
if (number > higherBound) number = higherBound;
return (int) Math.round((number - lowerBound) / increment);
}
public static void main(String... args) {
double lower = 2.3d;
double higher = 3.9;
double inc = 0.1d;
double[] inputs = { 0.5d, 2.25, 2.35, 2.4, 3.0, 3.8, 3.85, 3.9, 4.0 };
RangeFinder rf = new RangeFinder(lower, higher, inc);
System.out.format("Lower bound: %1.2f%n", lower);
System.out.format("Upper bound: %1.2f%n", higher);
System.out.format("Increment: %1.2f%n", inc);
for(double inp : inputs) {
System.out.format("Input: %1.2f\tOutput: %d%n",
inp, rf.getRange(inp));
}
}
}
例子:
Lower bound: 2.30
Upper bound: 3.90
Increment: 0.10
Input: 0.50 Output: 0
Input: 2.25 Output: 0
Input: 2.35 Output: 1
Input: 2.40 Output: 1
Input: 3.00 Output: 7
Input: 3.80 Output: 15
Input: 3.85 Output: 16
Input: 3.90 Output: 16
Input: 4.00 Output: 16