我有一个list
a
floats
,并尝试对每个元素应用上限maxV
和下限minV
,以便将元素的总和list
保持不变sumV
。这应该以一种方式完成,以便最小化总和(| a_new / a_orig - 1 |),其中||是绝对功能。
有人可以帮助改进以下方法:
>>> a, maxV, minV, sumV = [1.,2.,3.,4.,5.], 4.5, 2.1, 14
>>> import numpy as np
>>> a = np.copy(a)*sumV/np.sum(a)
>>> flr = a < minV
>>> cp = a > maxV
>>> while not (sum(flr) == 0 & sum(cp) == 0):
>>> a[flr] = minV
>>> a[cp] = maxV
>>> sumChanged = np.sum(a[flr | cp])
>>> sumUnchanged = np.sum(a[(~flr) & (~cp)])
>>> a[(~flr) & (~cp)] *= (sumV - sumChanged)/sumUnchanged
>>> flr = a < minV
>>> cp = a > maxV
>>> a
>>> array([ 2.1, 2.1, 2.27142857, 3.02857143, 4.5])
>>>