Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用舍入结果规范化数组(python、numpy、scipy)_Python_Numpy_Normalize - Fatal编程技术网

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

如何使用舍入结果规范化数组(python、numpy、scipy),python,numpy,normalize,Python,Numpy,Normalize,此外,这不是正确的代码。 如何使它正确,简短和美丽 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])

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

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

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]
如果你想保留2位小数,并强制设置为
1.0
,只需修改即可

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

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]
如果你想保留2位小数,并强制设置为
1.0
,只需修改即可

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

函数第二次调用的期望输出是什么?[0.2,0.6,0.2]结果之和应该等于1.0。函数第二次调用的期望输出是什么?[0.2,0.6,0.2]结果之和应该等于1.0。结果之和应该等于1.0。看起来不错。谢谢。结果之和应该等于1.0。看起来很棒。非常感谢。