【问题标题】:Numerical integration of array with array value as upper limit以数组值为上限的数组数值积分
【发布时间】:2021-07-23 06:07:19
【问题描述】:

所以我有以下代码:

import numpy as np
import scipy.special as spec
import scipy.integrate as integrate

a = array
b = constant * a
c = b*a/constant
e3 = spec.expn(3,c)

现在,我需要计算 e30a 的积分。由于 e3c 的函数,而 c 又是 a 的函数,所以我很难解决这个问题。 我尝试使用 loopintegrate.quadboth 来解决此问题,但我不断收到各种错误。
我在将 sutff 集成到 python 方面很新,所以任何帮助都将不胜感激。

【问题讨论】:

  • 你写a是一个数组,因此c也是一个数组。那么“从0到a”是什么意思?你得到什么样的错误?
  • 你能用数学符号解释一下你想计算什么吗?我知道 expn(n, x) 计算从 1 到 infty 的积分,它不是指数函数。
  • @RecencyEffect 我在各种尝试中遇到的一些错误(在调用 quad 函数时)是“TypeError:只有 size-1 数组可以转换为 Python 标量”或“ValueError:真值”具有多个元素的数组是不明确的。使用 a.any() 或 a.all()'。
  • @agus.dinamarca 数学符号是 $\int_{0}^{a} \Epsilon_3(c) da$。我应该补充一点,我尝试在集成之前迭代数组的值,但也许这是错误的方法?

标签: python arrays numpy scipy numerical-integration


【解决方案1】:

这里有一个可能的解决方案,请检查我是否正确理解了问题以及是否有用...

import scipy.special as spec
from scipy.integrate import quad
import numpy as np

array = np.array([0, 1, 2, 3, 4, 5])  # array[i] >= 0 for all i in [0, len(array) - 1]. For example, array = np.array([1, 2, 3, 4, 5])
constant = 3 # >= 0. For example, constant = 3


a = array
b = constant * a # multiply numpy array by a scalar (it is possible with numpy arrays (: )
c = b * a / constant

e3 = spec.expn(3, c)

# Some usefull explanations:

print('Output:', e3) # return a ndarray with the value of the integral e3 en each point specified in c (numpy array)
# Output: [1.09691967e-01 2.76136095e-03 1.04786279e-05 5.96855753e-09 4.97790975e-13]

# For evaluate the integral e3 from 0 to a[len(a) - 1]:
result1 = e3[len(a) - 1] - e3[0] 
print('Output:', result1)
# Output: -0.499999999950223

# Other thing is the integral of e3 from 0 to a[len(a) - 1]. You can use quad (return the value and an estimted error)
# See https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html
result2 = quad(lambda x: spec.expn(3, x), 0, c[len(a) - 1])
print('Output:', result2)
# Output: (0.3333333333328521, 4.440892098500626e-16)

# Note that integration limits are floats not arrays.

【讨论】:

  • 是的,这很好用。现在,如果我们要对此进行一些扩展:假设这次我从 spec.expn(3,c) (这将是一个数组)中获取结果,我将它乘以另一个数组 d,我想将它从 0 整合到 a。如何做到这一点?
  • 这将是两个数组相乘(它们必须具有相同的大小),您可以使用 numpy.multiply(d, spec.expn(3,x)) 来实现。但是,当您要集成时有一个例外。我必须更好地分析它发生的原因......
猜你喜欢
  • 2020-10-02
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2012-12-03
  • 2021-07-20
  • 2015-03-30
  • 2016-05-20
  • 2020-11-01
相关资源
最近更新 更多