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

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

问题描述

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

Example range 1 (minimum and maximum):

[40 ... 480]

范围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],通过减去10将第二个范围转换为[0-130].这样做是为了获得易于缩放的从零开始的间隔.
  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天全站免登陆