257

所以我想弄清楚如何取一个数字范围并将值缩小以适应一个范围。想要这样做的原因是我试图在 java swing jpanel 中绘制椭圆。我希望每个椭圆的高度和宽度在 1-30 的范围内。我有一些方法可以从我的数据集中找到最小值和最大值,但是直到运行时我才知道最小值和最大值。是否有捷径可寻?

4

8 回答 8

591

假设您要将范围缩放[min,max][a,b]. 您正在寻找满足

f(min) = a
f(max) = b

在您的情况下,a将是 1 和b30,但让我们从更简单的东西开始并尝试映射[min,max]到 range [0,1]

放入min一个函数并取出 0 可以通过

f(x) = x - min   ===>   f(min) = min - min = 0

所以这几乎就是我们想要的。但是当我们真正想要 1 时,放入max会给我们max - min。所以我们必须对其进行缩放:

        x - min                                  max - min
f(x) = ---------   ===>   f(min) = 0;  f(max) =  --------- = 1
       max - min                                 max - min

这就是我们想要的。所以我们需要进行平移和缩放。现在,如果我们想要获得 and 的任意值ab我们需要一些更复杂的东西:

       (b-a)(x - min)
f(x) = --------------  + a
          max - min

您可以验证 put in minfor xnow givea和 put in maxgive b

您可能还注意到这(b-a)/(max-min)是新范围大小和原始范围大小之间的比例因子。所以实际上我们首先是x通过进行转换-min,将其缩放到正确的因子,然后将其转换回 的新最小值a

于 2011-03-14T05:49:25.993 回答
64

这是一些用于复制粘贴的 JavaScript(这是 irritate 的回答):

function scaleBetween(unscaledNum, minAllowed, maxAllowed, min, max) {
  return (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed;
}

像这样应用,将范围 10-50 缩放到 0-100 之间的范围。

var unscaledNums = [10, 13, 25, 28, 43, 50];

var maxRange = Math.max.apply(Math, unscaledNums);
var minRange = Math.min.apply(Math, unscaledNums);

for (var i = 0; i < unscaledNums.length; i++) {
  var unscaled = unscaledNums[i];
  var scaled = scaleBetween(unscaled, 0, 100, minRange, maxRange);
  console.log(scaled.toFixed(2));
}

0.00、18.37、48.98、55.10、85.71、100.00

编辑:

我知道我很久以前就回答了这个问题,但这是我现在使用的更简洁的功能:

Array.prototype.scaleBetween = function(scaledMin, scaledMax) {
  var max = Math.max.apply(Math, this);
  var min = Math.min.apply(Math, this);
  return this.map(num => (scaledMax-scaledMin)*(num-min)/(max-min)+scaledMin);
}

像这样应用:

[-4, 0, 5, 6, 9].scaleBetween(0, 100);

[0, 30.76923076923077, 69.23076923076923, 76.92307692307692, 100]

于 2015-07-28T21:07:08.097 回答
31

为方便起见,这里是 Java 形式的 Irritate 算法。根据需要添加错误检查、异常处理和调整。

public class Algorithms { 
    public static double scale(final double valueIn, final double baseMin, final double baseMax, final double limitMin, final double limitMax) {
        return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin;
    }
}

测试人员:

final double baseMin = 0.0;
final double baseMax = 360.0;
final double limitMin = 90.0;
final double limitMax = 270.0;
double valueIn = 0;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 360;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 180;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));

90.0
270.0
180.0
于 2014-04-18T15:58:48.987 回答
28

我是这样理解的:


x在一个范围内的百分比是多少

假设您的范围从0100。给定该范围内的任意数字,它在该范围内的“百分比”是多少?这应该很简单,0将是0%50将是50%100将是100%

现在,如果你的范围是20怎么100办?我们不能应用与上述相同的逻辑(除以 100),因为:

20 / 100

没有给我们020应该是0%现在)。这应该很容易解决,我们只需要020. 我们可以通过减去:

(20 - 20) / 100

但是,这不再适用100,因为:

(100 - 20) / 100

不给我们100%。同样,我们也可以通过从分母中减去来解决这个问题:

(100 - 20) / (100 - 20)

找出x某个范围内的百分比的更通用等式是:

(x - MIN) / (MAX - MIN)

将范围缩放到另一个范围

现在我们知道了一个数字在一个范围内的百分比,我们可以应用它来将该数字映射到另一个范围。让我们通过一个例子。

old range = [200, 1000]
new range = [10, 20]

如果我们在旧范围内有一个数字,那么新范围内的数字是多少?假设数字是400。首先,找出400旧范围内的百分比。我们可以应用上面的等式。

(400 - 200) / (1000 - 200) = 0.25

因此,400位于25%旧范围内。我们只需要弄清楚25%新范围的数字是多少。想想是50%什么[0, 20]。会是10对的吗?你是怎么得出这个答案的?好吧,我们可以这样做:

20 * 0.5 = 10

但是,从[10, 20]呢?我们现在需要改变一切10。例如:

((20 - 10) * 0.5) + 10

一个更通用的公式是:

((MAX - MIN) * PERCENT) + MIN

对于 what 25%of的原始示例[10, 20]是:

((20 - 10) * 0.25) + 10 = 12.5

因此,400在范围内[200, 1000]将映射到12.5范围内[10, 20]


TLDR

从旧范围映射x到新范围:

OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN
于 2017-11-29T14:51:44.480 回答
12

我遇到了这个解决方案,但这并不真正符合我的需要。所以我在 d3 源代码中挖掘了一下。我个人会建议像 d3.scale 那样做。

所以在这里你将域缩放到范围。优点是您可以将标志翻转到目标范围。这很有用,因为计算机屏幕上的 y 轴自上而下,因此较大的值具有较小的 y。

public class Rescale {
    private final double range0,range1,domain0,domain1;

    public Rescale(double domain0, double domain1, double range0, double range1) {
        this.range0 = range0;
        this.range1 = range1;
        this.domain0 = domain0;
        this.domain1 = domain1;
    }

    private double interpolate(double x) {
        return range0 * (1 - x) + range1 * x;
    }

    private double uninterpolate(double x) {
        double b = (domain1 - domain0) != 0 ? domain1 - domain0 : 1 / domain1;
        return (x - domain0) / b;
    }

    public double rescale(double x) {
        return interpolate(uninterpolate(x));
    }
}

这是测试,您可以在其中看到我的意思

public class RescaleTest {

    @Test
    public void testRescale() {
        Rescale r;
        r = new Rescale(5,7,0,1);
        Assert.assertTrue(r.rescale(5) == 0);
        Assert.assertTrue(r.rescale(6) == 0.5);
        Assert.assertTrue(r.rescale(7) == 1);

        r = new Rescale(5,7,1,0);
        Assert.assertTrue(r.rescale(5) == 1);
        Assert.assertTrue(r.rescale(6) == 0.5);
        Assert.assertTrue(r.rescale(7) == 0);

        r = new Rescale(-3,3,0,1);
        Assert.assertTrue(r.rescale(-3) == 0);
        Assert.assertTrue(r.rescale(0) == 0.5);
        Assert.assertTrue(r.rescale(3) == 1);

        r = new Rescale(-3,3,-1,1);
        Assert.assertTrue(r.rescale(-3) == -1);
        Assert.assertTrue(r.rescale(0) == 0);
        Assert.assertTrue(r.rescale(3) == 1);
    }
}
于 2015-03-10T07:08:19.743 回答
2

我采用了 Irritate 的答案并对其进行了重构,以便通过将其分解为最少的常数来最小化后续计算的计算步骤。动机是允许缩放器在一组数据上进行训练,然后在新数据上运行(对于 ML 算法)。实际上,它很像 SciKit 为 Python 使用的预处理 MinMaxScaler。

因此,x' = (b-a)(x-min)/(max-min) + a(其中 b!=a) 变为x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a可以简化为 形式的两个常数x' = x*Part1 + Part2

这是一个带有两个构造函数的 C# 实现:一个用于训练,一个用于重新加载训练过的实例(例如,支持持久性)。

public class MinMaxColumnSpec
{
    /// <summary>
    /// To reduce repetitive computations, the min-max formula has been refactored so that the portions that remain constant are just computed once.
    /// This transforms the forumula from
    /// x' = (b-a)(x-min)/(max-min) + a
    /// into x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
    /// which can be further factored into
    /// x' = x*Part1 + Part2
    /// </summary>
    public readonly double Part1, Part2;

    /// <summary>
    /// Use this ctor to train a new scaler.
    /// </summary>
    public MinMaxColumnSpec(double[] columnValues, int newMin = 0, int newMax = 1)
    {
        if (newMax <= newMin)
            throw new ArgumentOutOfRangeException("newMax", "newMax must be greater than newMin");

        var oldMax = columnValues.Max();
        var oldMin = columnValues.Min();

        Part1 = (newMax - newMin) / (oldMax - oldMin);
        Part2 = newMin + (oldMin * (newMin - newMax) / (oldMax - oldMin));
    }

    /// <summary>
    /// Use this ctor for previously-trained scalers with known constants.
    /// </summary>
    public MinMaxColumnSpec(double part1, double part2)
    {
        Part1 = part1;
        Part2 = part2;
    }

    public double Scale(double x) => (x * Part1) + Part2;
}
于 2018-04-08T17:54:23.157 回答
2

根据 Charles Clayton 的回复,我加入了一些 JSDoc、ES6 调整,并在原始回复中纳入了评论中的建议。

/**
 * Returns a scaled number within its source bounds to the desired target bounds.
 * @param {number} n - Unscaled number
 * @param {number} tMin - Minimum (target) bound to scale to
 * @param {number} tMax - Maximum (target) bound to scale to
 * @param {number} sMin - Minimum (source) bound to scale from
 * @param {number} sMax - Maximum (source) bound to scale from
 * @returns {number} The scaled number within the target bounds.
 */
const scaleBetween = (n, tMin, tMax, sMin, sMax) => {
  return (tMax - tMin) * (n - sMin) / (sMax - sMin) + tMin;
}

if (Array.prototype.scaleBetween === undefined) {
  /**
   * Returns a scaled array of numbers fit to the desired target bounds.
   * @param {number} tMin - Minimum (target) bound to scale to
   * @param {number} tMax - Maximum (target) bound to scale to
   * @returns {number} The scaled array.
   */
  Array.prototype.scaleBetween = function(tMin, tMax) {
    if (arguments.length === 1 || tMax === undefined) {
      tMax = tMin; tMin = 0;
    }
    let sMax = Math.max(...this), sMin = Math.min(...this);
    if (sMax - sMin == 0) return this.map(num => (tMin + tMax) / 2);
    return this.map(num => (tMax - tMin) * (num - sMin) / (sMax - sMin) + tMin);
  }
}

// ================================================================
// Usage
// ================================================================

let nums = [10, 13, 25, 28, 43, 50], tMin = 0, tMax = 100,
    sMin = Math.min(...nums), sMax = Math.max(...nums);

// Result: [ 0.0, 7.50, 37.50, 45.00, 82.50, 100.00 ]
console.log(nums.map(n => scaleBetween(n, tMin, tMax, sMin, sMax).toFixed(2)).join(', '));

// Result: [ 0, 30.769, 69.231, 76.923, 100 ]
console.log([-4, 0, 5, 6, 9].scaleBetween(0, 100).join(', '));

// Result: [ 50, 50, 50 ]
console.log([1, 1, 1].scaleBetween(0, 100).join(', '));
.as-console-wrapper { top: 0; max-height: 100% !important; }

于 2020-03-03T19:48:02.810 回答
2

我有时会发现这个有用的变体。

  1. 将 scale 函数包装在一个类中,这样如果在多个地方缩放相同的范围,我就不需要传递最小值/最大值
  2. 添加两个小检查以确保结果值保持在预期范围内。

JavaScript 中的示例:

class Scaler {
  constructor(inMin, inMax, outMin, outMax) {
    this.inMin = inMin;
    this.inMax = inMax;
    this.outMin = outMin;
    this.outMax = outMax;
  }

  scale(value) {
    const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;

    if (result < this.outMin) {
      return this.outMin;
    } else if (result > this.outMax) {
      return this.outMax;
    }

    return result;
  }
}

此示例以及基于函数的版本来自页面https://writingjavascript.com/scaling-values-between-two-ranges

于 2020-09-13T23:27:20.243 回答