首页 > 解决方案 > 循环内的尖峰值

问题描述

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

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.
```

标签: pythonarraysnumpy

解决方案


将您的输入乘以 10 以给出整数值,答案就是您所期望的。

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


推荐阅读