在 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 只是常量(先前分配)。
当我然后尝试调用函数时:
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, ...)
函数,
Return an iterator that applies function to every item of iterable, yielding the results.
和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.
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()
我正在尝试计算以下积分
使用 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 只是常量(先前分配)。 当我然后尝试调用函数时:
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, ...)
函数,
Return an iterator that applies function to every item of iterable, yielding the results.
和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.
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()