• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Solving Equations

Contents

  • Solving Single Equation
  • Solving System of Equations
  • Visualization
  • Alternatives

A friend recently asked me if I could help her to find the solution to a system of non-linear equations. I remembered Sympy, a Python library for symbolic computations.

Installation is easy:

pip install sympy

Solving Single Equation

from sympy import Eq, symbols, solve

x = symbols("x")
eq = Eq(x ** 2, 9)
print(solve(eq))

And it returns [-3, 3]! Awesome! So it found all solutions for that single, simple equation!

Solving System of Equations

from sympy import Eq, symbols, solve

x, y = symbols("x y")
eq1 = Eq(x * y, 35)
eq2 = Eq(x + y, 12)
print(solve([eq1, eq2]))

This returns [{x: 5, y: 7}, {x: 7, y: 5}] 🎉

Visualization

Equations can get really complicated and typos happen easily. Rendering the equations in a nice way helps a lot to find bugs. I do this by starting a Jupyter Notebook. Just install jupyter and enter jupyter notebook in the console.

Add this to a cell in the notebook and execute it:

from sympy import init_printing

init_printing()

It looks like this:

Sympy in Jupyter Notebook
Sympy in Jupyter Notebook

Alternatives

  • Wolfram Mathematica (comparison): Pretty expensive, no Python binding

Published

Apr 21, 2020
by Martin Thoma

Category

Code

Tags

  • Computer Algebra System 1
  • Python 141
  • sympy 1

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor