Cap / Floor数字序列与原始序列的偏差最小

时间:2018-01-30 20:51:14

标签: python numpy minimization

我有一个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])
>>>

0 个答案:

没有答案