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.
```
解决方案
将您的输入乘以 10 以给出整数值,答案就是您所期望的。
如果要比较两个不同的浮点值列表的总和,则需要补偿浮点值的不精确性。
推荐阅读
- java - 如何使用 java selenium 重构按钮 webElement?
- excel - 当累积和达到一定条件时查找行
- php - 调用数组上的成员函数 where()
- selenium - Selenium Web 驱动程序如何单击 Span 类元素
- sql - Python - 定义查询的输出到变量
- java - Java 与 Cucumber 场景顺序
- python - 为什么 matplotlib 有这么多“制作”情节的选择?
- angular - 可观察内部可观察并将结果合并到其他
- spring-boot - 来自带有 Spring/Project 反应器的 HTTP 客户端的流响应
- java - java - 读取与jar文件相同目录中的配置文件