Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to integrate a composite function using scipy

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: must be real number, not function

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading