8765674
8765674

Reputation: 1234

Numerical integration Loop Python

I would like to write a program that solves the definite integral below in a loop which considers a different value of the constant c per iteration.

I would then like each solution to the integral to be outputted into a new array.

How do I best write this program in python?

enter image description here

with limits between 0 and 1.

from scipy import integrate

integrate.quad

Is acceptable here. My major struggle is structuring the program.

Here is an old attempt (that failed)

# 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)

Upvotes: 2

Views: 10435

Answers (3)

mgilson
mgilson

Reputation: 310049

You're really close.

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)

I think you're a little confused about how lambda works.

my_func = lambda x: 2*x

is the same thing as:

def my_func(x):
    return 2*x

If you still don't like lambda, you can do this:

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

#...snip...
integral, error = integrate.quad(f, 0, 1, args=(c,) )

Upvotes: 3

Nicolas Barbey
Nicolas Barbey

Reputation: 6797

For instance to compute the given integral for c in [0, 9] :

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

This is using list comprehension and lambda functions.

Alternatively, you could define the function which returns the integral from a given c as a ufunc (thanks to vectorize). This is perhaps more in the spirit of 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.])

Upvotes: 5

Andy Hayden
Andy Hayden

Reputation: 375675

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]

This will output a list of just like Nicolas answer, for whatever list of constants.

Upvotes: 0

Related Questions