Simplest way to solve mathematical equations in Python

Viewed 73472

I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.

It is simple to use wolframalpha.com, the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenience of an iPython shell.

Is there a simple library to work on linear and quadratic equations from a python shell?

Personally, I find it extremely convenient to use the Casio 991 MS scientific calculator. I know how to set variables, solve equations, and do a lot. I want such a tool preferably usable from within an ipython shell. I am surprised not to have found any. I'm not impressed enough by sage; perhaps I am missing something.

16 Answers

For reference: Wolfram Alpha's solution:

a-1000!=0,   b = (1000 (a-500))/(a-1000),   c = (-a^2+1000 a-500000)/(a-1000)

In python, using sympy's solver module (note that it assumes all equations are set equal to zero):

>>> import sympy
>>> a, b, c = sympy.symbols('a, b, c')
>>> sympy.solve([a + b + c - 1000, a**2 + b**2 - c**2], b, c)
[(1000*(a - 500)/(a - 1000), (-a**2 + 1000*a - 500000)/(a - 1000))]

And of course, a != 1000, as a-1000 is the denominator of the two equations.

Try applying Bisection method in py to find the root given an interval:

def f(x, rhs): # f(x) = e^x
    return math.e ** x - rhs # e^x = rhs -> e^x - rhs = 0

def solve(rhs, a = 0, b = 100, tol = 1e-3):
    while True:
        c  = (a + b) / 2.0
        if(f(a, rhs) * f(c, rhs) > 0):
            a = c
        else:
            b = c
        if(abs(f(c, rhs)) < tol):
            break
    return c

y = math.e ** 3.75 # x = 3.75
print(solve(y)) # 3.7499..

SymPy symbolic Python library demo: symbolically solving math and integrals & pretty-printing the output

From @Autoplectic:

sympy is exactly what you're looking for.

While I have a tendency to write some of the longest answers on Stack Overflow, that is the shortest answer I've seen on Stack Overflow.

Let's add a basic demo.

References and tutorials you'll need:

  1. https://www.sympy.org/en/index.html --> click "Get started with the tutorial"
    1. Tutorial index: https://docs.sympy.org/latest/tutorial/index.html Example pages:
      1. Basic Operations
      2. Printing
      3. Simplification
      4. Calculus

Calculus demo I came up with (see here for the main tutorial I looked at to get started):

Short version:

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
print(pretty(integral))
result = integral.doit() # "do it": evaluate the integral
print(pretty(result))

Longer version:

eRCaGuy_hello_world/math/sympy_integral_and_printing.py:

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

# Store an integral
integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
# print it in various ways
print("ORIGINAL INTEGRAL:")
print(pretty(integral))
pprint(integral)        # "pretty print": same as above
print(pretty(integral, use_unicode=False))  # pretty print with ASCII instead 
                                            # of unicode
print(integral)         # plain text
print(latex(integral))  # in LaTeX format

# Now solve the integral and output the result by telling it to
# "do it".
result = integral.doit()
# print it in various ways
print("\nRESULT:")
print(pretty(result))
pprint(result)
print(pretty(result, use_unicode=False))
print(result)
print(latex(result))

Note that using pprint(integral) is the same as print(pretty(integral)).

Output of running the above commands:

ORIGINAL INTEGRAL:
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
 oo  oo                 
  /   /                 
 |   |                  
 |   |      2    2      
 |   |   - x  - y       
 |   |  e          dx dy
 |   |                  
/   /                   
-oo -oo                 
Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty} e^{- x^{2} - y^{2}}\, dx\, dy

RESULT:
π
π
pi
pi
\pi

The SymPy symbolic math library in Python can do pretty much any kind of math, solving equations, simplifying, factoring, substituting values for variables, pretty printing, converting to LaTeX format, etc. etc. It seems to be a pretty robust solver in my very limited use so far. I recommend trying it out.

Installing it, for me (tested on Linux Ubuntu), was as simple as:

pip3 install sympy
Related