【问题标题】:How can i calculate linear interpolation between two numbers using given steps?如何使用给定的步骤计算两个数字之间的线性插值?
【发布时间】:2022-01-06 17:45:07
【问题描述】:

如何计算开始和停止之间的插​​值?

示例:插值(开始、停止、步进)

interpolation(1, 5, 1) -> [1.0]
interpolation(1, 5, 2) -> [1.0, 5.0]
interpolation(1, 5, 3) -> [1.0, 3.0, 5.0]
interpolation(1, 5, 4) -> [1.0, 2.333333333333333, 3.6666666666666665, 5.0]
interpolation(1, 5, 5) -> [1.0, 2.0, 3.0, 4.0, 5.0]
interpolation(5, 1, 5) -> [5.0, 4.0, 3.0, 2.0, 1.0]

【问题讨论】:

  • 我是否正确理解step=1 - 你需要返回[start]step=2 - [start, stop]
  • 我强烈建议为step 选择另一个名称,例如num_steps 或只是numstep 这个名字几乎总是用来表示“一个元素与下一个元素之间的差异”,而不是“元素的数量”。

标签: python python-3.x list math interpolation


【解决方案1】:

你可以使用numpy.linspace:

import numpy as np

np.linspace(5, 1, 5)
# array([5., 4., 3., 2., 1.])

np.linspace(1, 5, 4)
# array([1.        , 2.33333333, 3.66666667, 5.        ])

或者用纯python:

def interpolation(start, stop, step):
    if step == 1:
        return [start]
    return [start+(stop-start)/(step-1)*i for i in range(step)]

interpolation(5, 1, 5)
# [5.0, 4.0, 3.0, 2.0, 1.0]

interpolation(1, 5, 4)
# [1.0, 2.333333333333333, 3.6666666666666665, 5.0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2010-09-14
    • 2019-12-21
    相关资源
    最近更新 更多