简体   繁体   English

与 python 中的可变限制积分

[英]Integral with variable limits in python

I'm trying to compute the following integral我正在尝试计算以下积分

在此处输入图像描述

using scipy, with the following program:使用 scipy,使用以下程序:

def E(z):
    result = 1/np.sqrt(Om*(1 + z)**3 + Ode + Ox*(1 + z)**2)
    return result 

def r(z, E): 
    result, error  = quad(E, 0, z) # integrate E(z) from 0 to z
    return result

z being the independent variable, while Om Ode and Ox are simply constants (previously assigned). z 是自变量,而 Om Ode 和 Ox 是简单的常量(之前已分配)。 When I then try to call the function:然后当我尝试调用 function 时:

z = np.linspace(1e-3, 4, 300)
plt.plot(z, r(z))

I get the error我得到错误

flip, a, b = b < a, min(a, b), max(a, b)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() 
or a.all()

What is the problem?问题是什么? Is scipy.quad unable to integrate up to a variable? scipy.quad 是否无法积分到一个变量? Thank you so much for your help非常感谢你的帮助

You could use a combination of Python's map(function, iterable, ...) function,您可以使用 Python 的map(function, iterable, ...) function 的组合,

Return an iterator that applies function to every item of iterable, yielding the results.返回一个迭代器,它将 function 应用于可迭代的每个项目,产生结果。

and functools partial(func[,*args][, **keywords]) method:functools partial(func[,*args][, **keywords])方法:

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.返回一个新的部分 object,它在调用时的行为类似于使用位置 arguments 参数和关键字 arguments 关键字调用的 func。

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


def E(z):
    Om = 0.32
    Ode = 0.68
    Ox = 0
    result = 1/np.sqrt(Om*(1 + z)**3 + Ode + Ox*(1 + z)**2)

    return result


def r(z):
    result = np.array(
        list(map(partial(quad, E, 0), z))
    )[:, 0]  # integrate E(z) from 0 to z

    return result


z = np.linspace(1e-3, 4, 300)
fig, ax = plt.subplots()
ax.plot(z, r(z))
fig.show()

在此处输入图像描述

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

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