求阶跃函数和

2024-10-02 10:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有相当多的阶跃函数(大约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)

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


Tags: 函数代码fromimport间隔nprandomfold
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)])

以下是函数和的图:

^{pr2}$

enter image description here

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

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

11.945901591934897

使用substitution怎么样?{{cd2>

相关问题 更多 >

    热门问题