Convert symbolic math variables to programming language variables

Viewed 58

Suppose I have a program which asks me to input an equation to calculate something numerically.

I input 2*x+y as a string and it instantiates variable x and assigns numerical value to it then it instantiates variable y and assigns a value to it.

The result is calculated based on the equation that I input (Here it is 2*x+y)

x = 2
y = 3
result = 2*x + y
print(result)

I want to enter the equation symbolically and carry the rest of the equation numerically.

What is the best way to do so? (Looking for best practices to implement this idea so the program is able to scale for further development)

1 Answers

You can use eval function:

x = 2
y = 3
result = eval('2 * x + y')
print(result)

Output:

7

You can evaluate input algebraic equations as well:

x = 2
y = 3
equation = input("Enter the algebraic equation with x and y variables:")
print(f"The result is {eval(equation)}")

Output:

Enter the algebraic equation with x and y variables:x*5 - y*2
The result is 4

For more complex equations I would suggest sympy:

>>> from sympy.abc import x,y
>>> expr = 2*x + y
>>> expr.evalf(subs = {x:2, y:3})
7.00000000000000

You can checkout this and this for derivatives.

Related