You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按顶部底部指定比例压缩数值范围并编写数值映射函数

数值范围映射函数实现方案

原理说明

这一场景使用线性映射即可实现,转换过程不会改变原数值在区间内的相对分布位置。
核心参数定义:

  • 原输入区间:x ∈ [1, 100],区间总跨度为 100 - 1 = 99
  • 目标输出区间:y ∈ [25, 90],区间总跨度为 90 - 25 = 65

本题专用计算公式

y = 25 + (x - 1) * 65 / 99

边界验证:

  • 输入x=1时,输出y=25,符合底部压缩25%的要求
  • 输入x=100时,输出y=90,符合顶部压缩10%的要求

不同语言实现示例

Python 实现

def range_map(x: float) -> float:
    if x < 1 or x > 100:
        raise ValueError("输入值需在1-100区间内")
    return 25 + (x - 1) * 65 / 99

# 测试示例
print(range_map(1))    # 输出25.0
print(range_map(100))  # 输出90.0
print(range_map(50.5)) # 原区间中点,输出57.5,为目标区间中点

JavaScript 实现

function rangeMap(x) {
    if (x < 1 || x > 100) {
        throw new Error("输入值需在1-100区间内");
    }
    return 25 + (x - 1) * 65 / 99;
}

// 测试示例
console.log(rangeMap(1));    // 25
console.log(rangeMap(100));  // 90

通用区间映射方案

如果需要适配任意区间的映射需求,可以使用通用版本的函数,支持自定义原区间和目标区间:

y = 目标区间最小值 + (x - 原区间最小值) * (目标区间最大值 - 目标区间最小值) / (原区间最大值 - 原区间最小值)

Python通用版示例:

def universal_range_map(x: float, source_min: float, source_max: float, target_min: float, target_max: float) -> float:
    if x < source_min or x > source_max:
        raise ValueError(f"输入值需在{source_min}-{source_max}区间内")
    source_span = source_max - source_min
    target_span = target_max - target_min
    return target_min + (x - source_min) * target_span / source_span

# 本题调用示例
print(universal_range_map(100, 1, 100, 25, 90)) # 输出90.0

内容的提问来源于stack exchange,提问作者Enzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 01:45:04