如何使用舍入结果规范化数组(python、numpy、scipy)

2024-04-19 14:09:17 发布

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

此外,这不是正确的代码。 如何使它正确,简短和美丽

def normalize_weights(weights, threshold=0.01):
    total = sum(weights)
    result = [x / total for x in weights]
    result = [int((1.0 / threshold) * x) * threshold for x in result]
    result[-1] = 1.0 - sum(result[:-1])
    print(result)
    result[-1] = int((1.0 / threshold) * result[-1]) * threshold
    print(result)

normalize_weights([1.0, 1.0, 1.0])
[0.33, 0.33, 0.33999999999999997]
[0.33, 0.33, 0.34]  # ok

normalize_weights([1.0, 3.0, 1.0])
[0.2, 0.6, 0.19999999999999996]
[0.2, 0.6, 0.19]  # wrong

提前谢谢

编辑:结果之和应等于1.0


Tags: 代码in编辑forthresholddefokresult
1条回答
网友
1楼 · 发布于 2024-04-19 14:09:17
a = numpy.array([1.0,3.0,1.0])
normalized_a = numpy.round(a/numpy.linalg.norm(a,1.0),2)
# [0.2,0.6,0.2]

也许吧

a = numpy.array([1.0,1.0,1.0])
normalized_a = numpy.round(a/numpy.linalg.norm(a,1.0),2)
# [0.33,0.33,0.33]

如果你想有两个小数位并强制1.0,只需修正它

normalized_a[0] += 1.0 - numpy.sum(normalized_a) # we could just as easily fix the -1 index ...

相关问题 更多 >