循环内的峰值

2024-09-24 22:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个代码,以便从数组中的选项中确定适合给定值的适当数据集,如下所示:

import numpy as np

def find_nearest(array, value):
        array = np.asarray(array)
        idx = (np.abs(array - value)).argmin()
        return array[idx]


thickness = np.array([0.1,0.2,0.4,0.8,1.6,3.2,6.4,12.8,25.6,51.2])
b=np.array([])
a=100
c = 48.4
while c>=0 and a>0.1:
    a = find_nearest(thickness,c)

    if a > c:
        g = np.where(thickness==a)
        f = g[0]-1
        a = thickness[f]
    else:
        a = a
    c = c - a
    print(c)
    if c == 0.1:
        break
    b=np.append(b,a)
    itemindex = np.where(thickness==a)
    itemindex = itemindex[0]
    upper_limit = len(thickness)+1
    hj = np.arange(itemindex,upper_limit)
    thickness = np.delete(thickness,hj, None)
    print(thickness)
slots_sum = np.sum(b)
print("It will be used the following slots: ",b, "representing a total of {:.2f} mm".format(slots_sum))

但是,由于某些无法理解的原因,当代码试图找到正确的值组合以达到48.4时,代码跳过数组中的值0.4,并选择0.2和0.1,结果是48.3的和,而不是正确的48.4。我要绞尽脑汁好几天了,我会感谢你的帮助。你知道吗

[22.8]
[ 0.1  0.2  0.4  0.8  1.6  3.2  6.4 12.8]
[10.]
[0.1 0.2 0.4 0.8 1.6 3.2 6.4]
[3.6]
[0.1 0.2 0.4 0.8 1.6 3.2]
[0.4]
[0.1 0.2 0.4 0.8 1.6]
[0.2]
[0.1]
[0.1]
[]
It will be used the following slots:  [25.6 12.8  6.4  3.2  0.2  0.1] representing a total of 48.30 mm.
```


Tags: 代码ifvaluenp数组findwherearray
1条回答
网友
1楼 · 发布于 2024-09-24 22:27:45

把你的输入乘以10得到整数值,答案就是你所期望的。你知道吗

如果要比较两个不同的浮点值列表的和,则需要补偿浮点值的不精确性。你知道吗

相关问题 更多 >