【问题标题】:Numerical integration Loop Python数值积分 Loop Python
【发布时间】:2012-08-12 19:38:46
【问题描述】:

我想编写一个程序,在循环中求解下面的定积分,该循环考虑每次迭代的常数 c 的不同值。

然后我希望将积分的每个解输出到一个新数组中。

如何最好地用 python 编写这个程序?

限制在 0 和 1 之间。

from scipy import integrate

integrate.quad

这里可以接受。我的主要困难是构建程序。

这是一个旧的尝试(失败了)

# import c
fn = 'cooltemp.dat'
c = loadtxt(fn,unpack=True,usecols=[1])

I=[]
for n in range(len(c)):

    # equation
    eqn = 2*x*c[n]

    # integrate 
    result,error = integrate.quad(lambda x: eqn,0,1)

    I.append(result)

I = array(I)

【问题讨论】:

  • 欢迎来到 Stack Overflow!我们鼓励您research your questions。如果您有 tried something already,请将其添加到问题中 - 如果没有,请先研究并尝试您的问题,然后再回来。
  • 您希望使用哪种数值积分方法?梯形法则?辛普森法则?高斯正交?蒙特卡洛积分?还是您只想要内置的scipy.integrate.quadrature 功能?请指定其中一些详细信息并展示您当前的进度,我们很乐意为您提供帮助。
  • integrate.quad 在这里是可以接受的。更多的是构建程序来迭代我遇到的常量。
  • 如果c是常数,为什么不使用标准解c*x^2?
  • @RolandSmith,这里的 c 代表积分常数。

标签: python loops numpy integration scipy


【解决方案1】:

例如计算 [0, 9] 中 c 的给定积分:

[scipy.integrate.quadrature(lambda x: 2 * c * x, 0, 1)[0] for c in xrange(10)]

这是使用list comprehensionlambda functions

或者,您可以将返回给定 c 的积分的函数定义为 ufunc(感谢 vectorize)。这或许更符合 numpy 的精神。

>>> func = lambda c: scipy.integrate.quadrature(lambda x: 2 * c * x, 0, 1)[0]
>>> ndfunc = np.vectorize(func)
>>> ndfunc(np.arange(10))
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

【讨论】:

  • 这看起来不错。而不是 xrange(10) 我如何得到它来计算 c 等于数组中的值的积分?
  • 查看上面给出的替代解决方案
【解决方案2】:
constants = [1,2,3]

integrals = []                                  #alternatively {}

from scipy import integrate

def f(x,c):
    2*x*c

for c in constants:
    integral, error = integrate.quad(lambda x: f(x,c),0.,1.)
    integrals.append(integral)                 #alternatively integrals[integral]

这将输出一个列表,就像 Nicolas 的答案一样,对于任何常量列表。

【讨论】:

    【解决方案3】:

    你真的很亲密。

    fn = 'cooltemp.dat'
    c_values = loadtxt(fn,unpack=True,usecols=[1])
    
    I=[]
    for c in c_values: #can iterate over numpy arrays directly.  No need for `range(len(...))`
    
        # equation
        #eqn = 2*x*c[n] #This doesn't work, x not defined yet.
    
        # integrate 
        result,error = integrate.quad(lambda x: 2*c*x, 0, 1)
    
        I.append(result)
    
    I = array(I)
    

    我认为您对 lambda 的工作原理有些困惑。

    my_func = lambda x: 2*x
    

    与以下内容相同:

    def my_func(x):
        return 2*x
    

    如果你仍然不喜欢 lambda,你可以这样做:

    f(x,c):
       return 2*x*c
    
    #...snip...
    integral, error = integrate.quad(f, 0, 1, args=(c,) )
    

    【讨论】:

    • @ElizabethPor -- 我很高兴能提供帮助。祝您集成顺利。
    猜你喜欢
    • 2017-02-02
    • 2022-10-05
    • 1970-01-01
    • 2014-07-19
    • 2019-07-19
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多