繁体   English   中英

使用变量进行积分作为积分限制(python)

[英]Integration with variable as an integration limit ( python)

我需要与python进行集成,但限制之一是变量,而不是数字(从0到z)。

我尝试了以下方法:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import quad

    def  I(z,y,a):    #function I want to integrate

      I = (a*(y*(1+z)**3+(1-y))**(0.5))**(-1)

      return I

    def dl(z,y,a):  #Integration of I

      dl = quad(I, 0, z, args =(z,y,a))

      return dl

我的问题是dl(z,y,a)给了我一个数组,所以每当我要绘制或评估它时,我都会得到以下结果:

ValueError:具有多个元素的数组的真值不明确。

我不知道是否有解决方案。感谢进阶

编辑:在您的代码中,您应该只将args参数设置为agrs=(y, a) ,不应该包含z。 然后,您可以通过索引返回的元组的第一个元素来访问积分的结果。

实际上, quad返回一个元组。 元组中的第一个元素是您想要的重用。 由于我无法正常运行您的代码,因此我写了一些短代码。 我不确定这是否是您想要的:

def I(a):
    return lambda z, y: (a*(y*(1+z)**3+(1-y))**(0.5))**(-1)

def dl(z, y, a):
    return quad(I(a), 0, z, args=(y))

print(dl(1,2,3)[0])

结果:

0.15826362868629346

I调用quad的正确方法是:

In [20]: quad(I, 0, 10, args=(1,2))
Out[20]: (0.6984886554222364, 1.1361829471531105e-11)

正如龙文指出的那样, I的第一个参数是quad变化的z (y,a)quad不变地传递给I参数。

但是出现错误是因为您尝试使用数组作为z边界

In [21]: quad(I, 0, np.arange(3), args=(1,2))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-fbbfa9c0cd3f> in <module>()
----> 1 quad(I, 0, np.arange(3), args=(1,2))

/usr/local/lib/python3.5/dist-packages/scipy/integrate/quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
    313     if (weight is None):
    314         retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
--> 315                        points)
    316     else:
    317         retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,

/usr/local/lib/python3.5/dist-packages/scipy/integrate/quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
    362 def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
    363     infbounds = 0
--> 364     if (b != Inf and a != -Inf):
    365         pass   # standard integration
    366     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()

在函数中使用if命令时出现ValueError-另一个最近尝试执行相同操作的问题,请使用数组作为积分边界。 该帖子提供了更多的错误回溯,因此更容易发现问题。


如果不是这个ValueError,则您的3个args会产生另一个错误:

In [19]: quad(I, 0, 10, args=(10,1,2))
....
TypeError: I() takes 3 positional arguments but 4 were given

我认为quad接受向量值积分边界。 因此,在这种情况下,您实际上必须循环z或使用np.vectorize

Python的考虑是,将空列表(或可迭代)转换为布尔值时为false。 想象一下,您正在列出一些东西。

在进行计算时,您可能会考虑零向量[0,0,0],在线性alegbra中它可能被视为零,但不是空列表。

您的错误似乎来自非null检查。 正如其他答案所建议的那样,您误调用了函数,并提供了预期存在数字的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM