【发布时间】:2017-11-08 20:21:12
【问题描述】:
我在 Python 中使用lambda 函数定义了一个现有函数。该函数表示概率分布的 PDF。我想构建另一个代表 CDF 的 lambda 函数单线。
我不希望使用带有 def 关键字的单独函数定义。
以下是我一直在使用的代码部分:
import numpy as np
import scipy.integrate as integrate
#define range
dx=0.01
X = np.arange(0,13,dx)
#define a piecewise function for the spline
ul = 1.0
f_pdf = lambda x: np.piecewise(x, [x < ul, x >= ul], [x[x<ul],0])
f_cdf = lambda x: integrate.quad(f_pdf,0,x)
#print the function evaluations
print(f_pdf(X))
print(f_cdf(X))
请注意,我最近发现,对于分段定义,我需要在 x<ul 的情况下限制返回数组的范围,例如 x[x<ul],以便它能够正确处理不同大小的数组。
我从最后一个命令得到的错误包括:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-ff6550e6092c> in <module>()
13 #print the function evaluations
14 print(f_pdf(X))
---> 15 print(f_cdf(X))
<ipython-input-4-ff6550e6092c> in <lambda>(x)
9 ul = 1.0
10 f_pdf = lambda x: np.piecewise(x, [x < ul, x >= ul], [x[x<ul],0])
---> 11 f_cdf = lambda x: integrate.quad(f_pdf,0,x)
12
13 #print the function evaluations
/path/anaconda3/lib/python3.6/site-packages/scipy/integrate/quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
321 if (weight is None):
322 retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
--> 323 points)
324 else:
325 retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
/path/anaconda3/lib/python3.6/site-packages/scipy/integrate/quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
370 def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
371 infbounds = 0
--> 372 if (b != Inf and a != -Inf):
373 pass # standard integration
374 elif (b == Inf and a != -Inf):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
当我尝试让它返回与集成端点数组对应的值时。我认为函数integrate.quad不适合将数组作为集成端点,但是有没有合适的替代方案?
我正在使用 Python 3.6.1。
【问题讨论】:
标签: python python-3.x numpy lambda scipy