Skip to main content
 首页 » 编程设计

python之评估阶跃函数的总和

2024年10月17日8arxive

我有相当多(大约 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) 

但是,这会输出一个大的符号表达式而不是实际值,这正是我想要的。

请您参考如下方法:

由于您考虑的是数值函数,因此(在性能方面)使用 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]) 

显然,为了找到最大值,仅考虑包含在 t_values 中的 S 个时刻就足够了。对于这个例子,

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

11.945901591934897