876*_*674 2 python integration loops numpy scipy
我想编写一个程序,在循环中解决下面的定积分,该循环考虑每次迭代的常数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)
Run Code Online (Sandbox Code Playgroud)
例如,计算[0,9]中c的给定积分:
[scipy.integrate.quadrature(lambda x: 2 * c * x, 0, 1)[0] for c in xrange(10)]
Run Code Online (Sandbox Code Playgroud)
或者,您可以定义函数,该函数将给定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.])
Run Code Online (Sandbox Code Playgroud)