2

我想编写一个程序,在循环中求解下面的定积分,该循环考虑每次迭代的常数 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)
4

3 回答 3

5

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

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

这是使用列表理解lambda 函数

或者,您可以定义从给定 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.])
于 2012-08-16T12:59:50.930 回答
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,) )
于 2012-08-16T13:03:51.437 回答
0
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 答案的列表。

于 2012-08-16T13:03:27.403 回答