2016-08-18 104 views
2

我有一個相當大的數量(大約1000)的步功能,每個只有兩個間隔。我想總結一下,然後找到最大值。做這個的最好方式是什麼?我已經試過了sympy,其代碼如下:評估步功能的總和

from sympy import Piecewise, piecewise_fold, evalf 
from sympy.abc import x 
from sympy.plotting import * 
import numpy as np 

S = 20 

t = np.random.random(20) 

sum_piecewise = None 

for s in range(S): 
    p = Piecewise((np.random.random(), x<t[s]), (np.random.random(), x>=t[s])) 
    if not sum_piecewise: 
     sum_piecewise = p 
    else: 
     sum_piecewise += p 

print sum_piecewise.evalf(0.2) 

然而,這種輸出了大量象徵性的表達,而不是實際的價值,這就是我想要的。

+0

的參數'evalf'是數字計算的數量。如果你想使用'subs(x,0.2)'或'evalf(subs = {x:0.2})'替換一個值。 – asmeurer

回答

0

怎麼樣使用substitution?嘗試通過sum_piecewise.subs(x, 0.2)更改

2

由於看起來您考慮了數值函數,因此使用Numpy更好(就性能而言)。這裏有一個方法:

import numpy as np 
import matplotlib.pyplot as plt 

np.random.seed(10) 
S = 20 # number of piecewise functions 

# generate S function parameters. 
# For example, the k-th function is defined as equal to 
# p_values[k,0] when t<t_values[k] and equal to 
# p_values[k,1] when t>= t_values[k] 
t_values = np.random.random(S) 
p_values = np.random.random((S,2)) 

# define a piecewise function given the function's parameters 
def p_func(t, t0, p0): 
    return np.piecewise(t, [t < t0, t >= t0], p0) 

# define a function that sums a set of piecewise functions corresponding to 
# parameter arrays t_values and p_values 
def p_sum(t, t_values, p_values): 
    return np.sum([p_func(t, t0, p0) for t0, p0 in zip(t_values,p_values)]) 

這裏是函數的總和的情節:

t_range = np.linspace(0,1,1000) 
plt.plot(t_range, [p_sum(tt,t_values,p_values) for tt in t_range]) 

enter image description here

顯然,爲了找到最大的,就足夠了只考慮S時間時刻包含在t_values。對於這個例子,

np.max([p_sum(tt,t_values,p_values) for tt in t_values]) 

11.945901591934897