繁体   English   中英

与 python 中的可变限制积分

[英]Integral with variable limits in python

我正在尝试计算以下积分

在此处输入图像描述

使用 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 是自变量,而 Om Ode 和 Ox 是简单的常量(之前已分配)。 然后当我尝试调用 function 时:

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

我得到错误

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()

问题是什么? scipy.quad 是否无法积分到一个变量? 非常感谢你的帮助

您可以使用 Python 的map(function, iterable, ...) function 的组合,

返回一个迭代器,它将 function 应用于可迭代的每个项目,产生结果。

functools partial(func[,*args][, **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