1

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)

M.Jones
  • 135
  • 6

1 Answers1

0

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.

Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
  • What if the equation contained differential operator? Like derivative of a variable `dy/dx` ? Then I cannot use `eval` and this is not a proper way to handle it. – M.Jones Mar 26 '22 at 04:55
  • @M.Jones I dont think we can differentiate with `eval()` but you can take a look at [this](https://stackoverflow.com/questions/44269943/how-do-you-evaluate-a-derivative-in-python) and [this](https://stackoverflow.com/questions/38176865/implicit-differentiation-with-python-3). – Abhyuday Vaish Mar 26 '22 at 04:58
  • @M.Jones I have edited my answer for `sympy` as well. – Abhyuday Vaish Mar 26 '22 at 05:11
  • The links you have provided address the symbolic derivative calculation. I want to input derivative operator in my equation then identify the string and calculate that derivative numerically(with whatever algorithm I have defined for calculating the derivative numerically) not strictly what sympy has defined. In addition, I might want to define a custom operator with a specific algorithm and this does not address the issue – M.Jones Mar 26 '22 at 05:20
  • @M.Jones Well, I would suggest you either edit this question(as you are asking a whole new question right now) or accept the answer and ask a new question about the derivative part. – Abhyuday Vaish Mar 26 '22 at 05:28
  • @M.Jones This is because in that case, my answer won't be valid regarding your derivative question. To prevent any misunderstanding or chaos you can ask for a new one :) – Abhyuday Vaish Mar 26 '22 at 05:28