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 interpret sin(x) with eval() in python

I am trying to allow the user to type sin(x) - y to set up an equation using SymPy, however, with my current code, when you input this, it returns:

TypeError: can’t convert expression to float

My current code is:

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

import numpy as np
import sympy as sp
import math
from math import sin, cos, tan

x, y = sp.symbols('x y')
literalEq = input("Enter equation")
eq = eval(literalEq)

I am quite new to using SymPy, could you please help me out?

>Solution :

It seems like you are trying to put directly x and y in the input which are mainly counted as expressions instead of anything else. You need to put the direct values like sin(3) - 5 which will return -4.858879991940133.

Or you can use sympify function to make the equation sympified to work on it using evalf function.

import sympy
from sympy import *
init_printing(use_unicode=True)

x, y = sympy.symbols('x y')
literalEq = str(input("Enter equation "))
literalEq = sympify(literalEq)
literalEq = literalEq.evalf()
pprint(literalEq) #For pretty printing

Or importing sin (and/or your required trigonometric functions) from sympy also works.

import sympy
from sympy import * #or from sympy import sin
init_printing(use_unicode=True)

x, y = sympy.symbols('x y')
literalEq = input("Enter equation ")
eq = eval(literalEq)
pprint(eq)
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