0

I want to integrate a product of two functions x(t)*p1(t) as t goes from -1 to 1. At the moment I have this code written:

import scipy.integrate as s
import numpy as np

p1 = lambda t: 1
p2 = lambda t: t
p3 = lambda t: (3*(t**2)-1)/2

x = lambda t: abs(t)

integral = s.quad(x*p1, -1, 1)
print(integral)

However, I am getting the following error:

TypeError: unsupported operand type(s) for *: 'function' and 'function'

Is it possible to combine two lambda functions symbolically to integrate them? I could define a function xp1 = lambda t: x(t)*p1(t), but since I have to do this for all pn, this seems kinda inefficient.

Is there a cleaner way to do this?

1
  • Python functions, lambda or not, are not symbolic. As you see there's no such thing as function multiply. What the inefficiency that you worry about? Runtime? or your keyboard time? Commented Sep 4, 2020 at 16:00

1 Answer 1

2

If you want to find a definitive integral (just the integration result value, when limits are given, like in your case) you don't need any symbolics, in fact it would only complicate your life and slowed down the computation.

In order to find the definitive integral of a multiplication of f1() and f2() you simply do:

import scipy.integrate as s
import numpy as np

def f1(t):
    return np.abs(t)

def f2(t):
    return (3*(t**2)-1)/2

def f(t):
    return f1(t) * f2(t)

integral = s.quad(f, -1, 1)
print(integral)
# or, if you like lambda functions ;-)
integral = s.quad(lambda t: f1(t)*f2(t), -1, 1)
print(integral)

Where I used only f1 and f2 for demonstration, since you defined more functions that you were actually trying to integrate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.