how to integrate a composite function using scipy
Question:
I have two functions defined as integrals where the lower and upper limits are (0-1) and (0-10), respectively. I found out the scipy
library and was trying to use it for this purpose. Below I am showing my functions.
f(x) = (p*x) dx
g(x) = alpha*(ln(f(x))) dx
I am trying to calculate the value of function g(x)
, but I could not find how to connect those two functions since they are composite functions.
import numpy as np
import math
from scipy.integrate import quad
def firstMethod(x, p1):
return p1 * x
def firstIntegral():
return quad(firstMethod, 0, 1, args=(4))[0]
def secondMethod(x, alpha):
return alpha*math.log(firstIntegral)
def secondIntegral():
return quad(secondMethod, 0, 10, args=(0.5))[0]
print(secondIntegral())
I am receiving the error of
TypeError: must be real number, not function
Answers:
The problem is in secondMethod
. Right now you’re passing the function firstIntegral
itself (functions are first class objects in Python). You need to call the function, i.e. put parentheses after its name and pass in any arguments it needs.
For example, you could change your secondMethod
to this:
def secondMethod(x, alpha):
return alpha * math.log(firstIntegral()) # Call the function.
It returns 3.4657359027997265
.
I have two functions defined as integrals where the lower and upper limits are (0-1) and (0-10), respectively. I found out the scipy
library and was trying to use it for this purpose. Below I am showing my functions.
f(x) = (p*x) dx
g(x) = alpha*(ln(f(x))) dx
I am trying to calculate the value of function g(x)
, but I could not find how to connect those two functions since they are composite functions.
import numpy as np
import math
from scipy.integrate import quad
def firstMethod(x, p1):
return p1 * x
def firstIntegral():
return quad(firstMethod, 0, 1, args=(4))[0]
def secondMethod(x, alpha):
return alpha*math.log(firstIntegral)
def secondIntegral():
return quad(secondMethod, 0, 10, args=(0.5))[0]
print(secondIntegral())
I am receiving the error of
TypeError: must be real number, not function
The problem is in secondMethod
. Right now you’re passing the function firstIntegral
itself (functions are first class objects in Python). You need to call the function, i.e. put parentheses after its name and pass in any arguments it needs.
For example, you could change your secondMethod
to this:
def secondMethod(x, alpha):
return alpha * math.log(firstIntegral()) # Call the function.
It returns 3.4657359027997265
.