Search code examples
pythonpython-3.xtypeerrorsympytaylor-series

Python : sympy TypeError: can't convert expression to float


Currently, I'm working on a calculator, that works similar to a 'real' calculator, when determining definite integrals.

Currently i can get it to work with functions such as

  • sin(x)
  • cos(x)
  • e**x
  • n*x**x

However, it won't accept math.sqrt(x) as a function in my code, where it simply states, that

File "C:\Users\Nikolai Lund Kühne\.spyder-py3\integration.py", line 6, in <module>
  print(series(math.sqrt(x), x, x0=0, n=6))

File "C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\expr.py", line 327, in __float__
  raise TypeError("can't convert expression to float")

TypeError: can't convert expression to float

My code is:

from sympy.functions import sin,cos
from sympy.abc import x
from sympy import series
from pprint import pprint
# Indsæt her funktionen f(x), variablen x, udviklingspunktet x0 og antal led n
print(series(math.sqrt(x), x, x0=0, n=6))

N = int(input("Antal summer(flere summer er mere præcist): "))
a = int(input("Integrer fra: "))
b = int(input("Integrer til: "))

# Vi anvender Midpoint metoden til integration og skriver funktionen ind, som skal integreres

def integrate(N, a, b):
    def f(x):
        return series(math.sqrt(x), x, x0=0, n=6)
    value=0
    value=2
    for n in range(1, N+1):
        value += f(a+((n-(1/2))*((b-a)/N)))
    value2 = ((b-a)/N)*value
    return value2

print("...................")
print("Her er dit svar: ")
print(integrate(N, a, b))

Can anyone help me here, it's greatly appreciated.

Disclaimer: I am quite new to programming and Python and would appreciate any help given. Sorry for the strange setup, I am used to LaTeX and MathJax when writing questions :)


Solution

  • You get the error:

    TypeError: can't convert expression to float
    

    Since the argument passed as expr is math.sqrt(x), and sympy doesn't expect that.

    Change from math.sqrt(x) to x**0.5:

    print(series(x**0.5, x, x0=0, n=6))
    

    The same applies to line 16.