Exploring the Sympy Library

July 23, 2023

I’ve talked a lot about programming during this 66 Days of Math adn Programming challenge and haven’t done much math. So today we’ll hang out with my math friend once again.

But there’s a catch.

Yeah we’re talking about math, but we’re talking about math with programming.

Yup, it’s a freaking double whammy today.

Last night I read through some of the Sympy library’s documentation, so I’ll write about it now.

Here’s what’s in today’s blog post:

  • Square roots with Math vs Sympy
  • How to define variables like x and y
  • How to show equality without equal signs

Let’s do it…

Square Roots with Math vs Sympy

Both of these Python libraries have built-in sqrt() functions. And they look exactly the same when writing code. But the difference lies in the values they print.

The math.sqrt() function returns a float.

using math library for square roots

The sympy.sqrt() function returns either an integer or number in radical form.

Using Sympy library for square roots

You may be thinking, who cares Mike, radical form vs decimal form means nothing. Those numbers are the same.

But I’m sorry to disappoint you, my friend because they are completely different.

You see, the square root of a non-perfect square creates an irrational number. And irrational numbers have infinitely many decimal places. So saying the square root of 15 equals 3.872983346207417 is not 100% accurate.

But saying the square root of 15 equals “3 rad 2” sounds like music to my ears.

How to Define Variables Like x and y

As a math major I’m no stranger to seeing letters more than numbers in math. Some of my best friends in college were x, y, and z. (Sadly I’m not joking).

But Python doesn’t let you define variables to use in math equations.

Not until Sympy came along, at least…

Using the symbols() function, you can define variables as I do below…

And this is useful when you want to write math equations or functions without solving them.

Creating symbols using Sympy

How to Show Equality Without Equal Signs

You can’t say “math equation” without “equal sign (=).”

But Sympy isn’t friendly with Python’s built-in = and == operators. Honestly, they’re kinda like enemies if you ask me.

That’s because Python doesn’t use equal signs the way a math person would. (=) is used to define variables, not to show equality. And while (==) shows equality, it shows structural equality. That is, it asks, “Does x equal y?” Not, “When does x equal y?”

Luckily Sympy has a built-in Eq() function we can use to show function equality…

Showing function equality with Sympy

Wrapping Up

I won’t lie.

I have a lot more to write about regarding Sympy. But there’s not enough time to do all of it in one blog post. If I tried that, I would have just rewritten the Sympy documentation.

So if you’re looking to learn more about Sympy, check out its documentation here.