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?
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)
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,) )