Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equation solver in Python

Given a simple equation such as:

x = y + z

You can get the third variable if you bind the other two (ie: y = x - z and z = x - y). A straightforward way to put this in code:

def solve(args):
    if 'x' not in args:
        return args['y'] + args['z']
    elif 'z' not in args:
        return args['x'] - args['y']
    elif 'y' not in args:
        return args['x'] - args['z']
    else:
        raise SomeError  

I obviously can take an equation, parse it and simplify it to achieve the same effect. But I believe in doing so I would be re-inventing the wheel. So where's my ready-made wheel?

like image 642
Aillyn Avatar asked Feb 09 '26 15:02

Aillyn


1 Answers

Consider using Sympy. It includes various tools to solve equations and a lot more.

The following is an excerpt from the docs:

>>> from sympy import I, solve
>>> from sympy.abc import x, y

>>> solve(x**4-1, x)
[1, -1, -I, I]
like image 102
Alexander Gessler Avatar answered Feb 12 '26 14:02

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!