如何使用舍入结果对数组进行标准化(python,numpy,scipy)

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

还不是正确的代码。如何使其正确,简短和美观?

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

预先感谢

python numpy normalize
1个回答
0
投票
a = numpy.array([1.0,3.0,1.0])
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])
numpy.round(a/numpy.linalg.norm(a,1.0),2)
# [0.33,0.33,0.33]
© www.soinside.com 2019 - 2024. All rights reserved.