Java双缩放

时间:2013-04-13 00:25:51

标签: java

如果我在x - y的范围内有一个双精度数,我怎样才能将这个双精度缩放到新的范围a-b

例如从-1转换为> 1至0 - > 1

由于 马丁

1 个答案:

答案 0 :(得分:3)

/**
 * @param value The incoming value to be converted
 * @param low1  Lower bound of the value's current range
 * @param high1 Upper bound of the value's current range
 * @param low2  Lower bound of the value's target range
 * @param high2 Upper bound of the value's target range
 */
public static final double map(double value, double low1, double high1, double low2, double high2) {

    double diff = value - low1;
    double proportion = diff / (high1 - low1);

    return lerp(low2, high2, proportion);
}

// Linearly interpolate between two values
public static final double lerp(double value1, double value2, double amt) {
    return ((value2 - value1) * amt) + value1;
}

http://developmentality.wordpress.com/2009/12/15/useful-utility-functions-0-of-n/

在您的情况下,您可以致电map(x, -1, 1, 0, 1)