评估步骤函数的总和

时间:2016-08-18 10:19:08

标签: python numpy scipy sympy

我有一个相当大的数量(大约1000)的阶梯函数,每个阶梯函数只有两个间隔。我想总结一下,然后找出最大值。做这个的最好方式是什么?我已尝试过同意,代码如下:

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)

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

2 个答案:

答案 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])

enter image description here

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

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

11.945901591934897

答案 1 :(得分:0)

使用substitution怎么样?尝试按sum_piecewise.evalf(0.2)

更改sum_piecewise.subs(x, 0.2)