0

I would very much like to implement analytical integration in my calculator. I have used numerical integration prior to this attempt with success. However, I can't seem to make my code work. I'm using the scipy.integrate module and the error code I get is TypeError: can't convert expression to float

My code is:

from sympy.functions import sin,cos,tan
from sympy.abc import x
from sympy import series
import scipy.integrate as integrate
import scipy.special as special

function1   = str(input("The function that should be expanded: "))
x0          = float(input("Point of developement: "))
n           = 1 + int(input("Grade of polynomial: "))
# input 0 -> n=1 -> konstant  (1 term, konstant)
# input 1 -> n=2 -> lineær    (2 termer, konstant + linear)
# input 2 -> n=3 -> kvadratisk (3 termer, konstant + linear + kvadratisk)
# ...

function2 = series(function1, x, x0, n)
print(function2)

a = float(input("Integrate from: "))
b = float(input("Integrate to: "))

def f(x):
    return function2.removeO()

x = Symbol('x')
result = integrate.quad(lambda x: f(x), a, b)

print("...................")
print("Here is your answer: ")
print(result)

I believe it might be due to the code using different modules (sympy and scipy) or that I just need to convert the expression in some way. I attempted to use lambdify but without success.

def f(x):
    return function2.removeO()
lam_f = lambdify(x, f(x))
result = integrate.quad(lambda x: lam_f, a, b)

And got another TypeError, since lambdify turns the expression into a function instead.

Can anyone help?

Nikolai
  • 39
  • 6
  • 1
    Some form of this question has been asked more than once here on StackOverflow. For example, see if https://stackoverflow.com/questions/48519770/conversion-of-symbolic-expression-to-numeric-one-for-use-in-quad-use-lambdify or https://stackoverflow.com/questions/40193323/sympy-using-a-symbolic-expression-as-a-numerical-integrand answer your question. – Warren Weckesser Sep 21 '20 at 08:32
  • 1
    result = intregrate.quad(lam_f, a,b) - since integrate.quad needs a function that returns something that can be converted to a float. – Iñigo González Sep 21 '20 at 08:50
  • I have no idea why i didn't try that @Iñigo it works wonderfully! Thank you! – Nikolai Sep 21 '20 at 08:57
  • 1
    For analytic integration you should use sympy's integrate rather than the scipy one. – Oscar Benjamin Sep 21 '20 at 11:41
  • @OscarBenjamin thank you aswell, I just fixed that and furthermore this means I don't have to use lambdify. Effiency for the win! – Nikolai Sep 21 '20 at 13:19

0 Answers0