将数字从一个范围翻译到另一个范围 [英] Translate numbers from a range to another range

查看:41
本文介绍了将数字从一个范围翻译到另一个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例范围 1(最小值和最大值):

Example range 1 (minimum and maximum):

[40 ... 480]

范围 1 中的示例数字:

Example numbers from range 1:

[42, 59.4, 78.18, 120.43, 416]

示例范围 2:

[10 .. 140]

如何将范围 1 中的数字值转换为第二范围内的值?42 应该相当于新范围内的 10 到 11 之间的值.

How can I translate the values of the numbers from range 1 to values within the second range? 42 should be equivalent to something between 10 and 11 in the new range.

我正在使用 PHP,但这更像是一道数学题.

I'm using PHP but this is more like a math problem.

我知道如何将它们与第二个范围对齐:

I know how to align them to the second range:

$diff = $range[0] - $numbers[0];
foreach($numbers as $i => $number){
  $numbers[$i] = $number + $diff;
}

但就是这样:(

推荐答案

您可以使用此函数将一个范围转换为另一个范围(python)

You can transform one of the ranges into the other with this function (python)

def transfrom(x):
    return (x - 40)*(130/440.0) + 10

一般来说,您希望重新设置范围(确保它们都从零开始),然后找到您需要如何拉伸第一个范围以获得第二个范围.所以步骤是

In general the idea is that you want to rebase the ranges (make sure that they both start at zero) and then find how you need to stretch the first range to obtain the second range. So the steps would be

  1. 通过减去 40 将第一个范围转换为 [0-440],通过减去 将第二个范围转换为 [0-130]代码>10.这样做是为了获得从零开始的易于扩展的间隔.
  2. 要将 [0-440] 中的任何值转换为 [0-130] 中的相应值,您需要将其乘以 130/440.您可以将其想象为通过除以 440 将第一个区间缩小到 [0-1] 区间,然后将其拉伸到 [0-130] 间隔乘法.
  3. 现在你知道如何从 [0-440][0-130] 并且这意味着从 [40-440][10-140] 您首先需要通过减去 40 乘以 130/440 来变基,然后添加 10
  1. Convert the first range to [0-440] by subtracting 40 and the second range to [0-130] by subtracting 10. This is done to get intervals which start at zero which are easy to scale.
  2. To convert any value from [0-440] to a corresponding value from [0-130] you need to multiply it with 130/440. You can imagine this as shrinking the first interval to a [0-1] interval by dividing with 440 and then stretching it to a [0-130] interval by multiplying.
  3. Now you know how to go from [0-440] to [0-130] and that means that to go from [40-440] to [10-140] you first need to rebase by subtracting 40 multiply by 130/440 and then add 10

例子:

>>> transform(40)
10.0
>>> transform(42)
10.590909090909092
>>> transform(220)
63.181818181818187
>>> transform(480)
140.0

这篇关于将数字从一个范围翻译到另一个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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