Saturday, May 12, 2018

Simple Equations in Sympy

Simple Equation Solution with sympy

Thanks to sympy, even if you forgot highschool math, you can still do highschool math. Sympy is part of the basic Anaconda distribution, so there is no prep work needed to try it out in an Anaconda environment. Below, a simple quadratic equation with integer solutions, solved with sympy. A notebook can be downloaded for the code below.

In [5]:
# setup
from sympy.solvers import solve
from sympy import Symbol
# prepare to work with single unknown
x = Symbol('x')
type(x)
Out[5]:
sympy.core.symbol.Symbol

So that we can be sure the sympy solution is correct, we'll start with something where we know the answer. This quadratic should have solutions at -3 and 2.

(x + 3) * (x - 2) = 0

x^2 + x - 6 = 0

The solve function from sympy.solver looks for 2 arguments, the equation to solve and the symbol to solve for.

In [7]:
solve (x**2 + x - 6, x)
Out[7]:
[-3, 2]

1 comment:

  1. A little of extra indentation because I am learning to make blog posts directly out of jupyter notebooks, which is a little harder than I expected.

    ReplyDelete