在给定浮点索引位置的情况下从字典中插入数据

问题描述 投票:0回答:1

我有一个 json 文件,其中包含给定温度下的扭矩数据数据元组。假设我从 46 度部分提取数据:

j = {"46": [[88.0, 95.3], [86.1, 93.4], [84.2, 91.3], [82.8, 89.7], [80.8, 87.8]]}

如果然后给我一个浮点数作为参考索引位置,例如:

index = 1.85

是否可以仅使用浮点索引位置从数据中进行插值? 显然,如果我尝试使用直线浮动作为索引位置,它会给我:

TypeError: list indices must be integers or slices, not float

目前我正在找到浮点上方和下方最接近的整数,然后手动插值,但这很乏味。我需要对元组中给出的两个数字进行插值..例如,在索引

1.85
我正在做:

lower_first_num = j["46"][1][0]
upper_first_num = j["46"][2][0]

difference = lower_first_num - upper_first_num
result = lower_first_num - (difference * .85)

其中 0.85 是两个指数点之间的百分比。然后我必须对元组中的第二个数字再次执行此操作。

关于给定的索引浮点数,它们可能是许多不同的数字,因为该程序将使用不同的数字运行数百次。

我只是想知道是否有一个可以使用的预构建方法...

python json dictionary floating-point interpolation
1个回答
0
投票

如果您希望在值之间进行线性插值,您很可能只需稍微调整代码即可,使用

math.floor
math.ceil
函数来获取给定索引上方和下方的索引。模 (
%
) 运算符允许我们获取小数位。

这样的东西就足够了:

from math import floor, ceil

data = j["46"] # [[88.0, 95.3], [86.1, 93.4], [84.2, 91.3], [82.8, 89.7], [80.8, 87.8]]

index = 1.85

before, after = data[floor(index)][0], data[ceil(index)][0] # 86.1, 84.2
step = index % 1 # .85
difference = after - before # -1.9
lerped_value = before + step * difference # 84.485

print(lerped_value) # 84.485

下面是一个图像(使用 Desmos 创建),其中绿色虚线代表每个点之间的线性插值,红色虚线代表索引 = 1.85,红点是插值点(1.85,84.485)。

您也可以将其编写为函数,我在下面包含了其中的一些变体,所有这些变体都隐含地假设您正在导入

floor
ceil

def interpolate(data : list[list[float]], index : float) -> float:
    before, after = data[floor(index)][0], data[ceil(index)][0]
    step = index % 1
    difference = after - before
    lerped_value = before + step * difference
    return lerped_value
def interpolate(data : list[list[float]], index : float) -> float:
    before, after = data[floor(index)][0], data[ceil(index)][0]
    return before + (index % 1) * (after - before)
def interpolate(data : list[list[float]], index : float) -> float:
    return (before := data[floor(index)][0]) + (index % 1) * (data[ceil(index)][0] - before)

您选择哪一个最终取决于个人喜好。为了简洁和清晰之间的平衡,我更喜欢第二种。

最后一点,您可能还想对您的点执行线性回归,因为这可能对数据中的错误不太敏感,并且如果您的数据是线性的,则会产生更平滑的整体曲线。

© www.soinside.com 2019 - 2024. All rights reserved.