Skip to article frontmatterSkip to article content
from __init__ import install_dependencies

await install_dependencies()

Run the following to load the SymPy module for symbolic computations in Python.

from sympy import *

The following code is a Python one-liner that creates a symbolic calculator.

S(input())

Evaluate the cell repeatedly with Ctrl+Enter to try some calculations below using this calculator:

  1. 23 by entering 2**3;
  2. 23\frac23 by entering 2/3;
  3. 32\left\lceil\frac32\right\rceil by entering 3//2;
  4. 3mod23\mod 2 by entering 3%2;
  5. 2\sqrt{2} by entering 2**(1/2); and
  6. sin(π/6)\sin(\pi/6) by entering sin(pi/6);

Unlike eval(input()), JupyterLab render the LaTeX\LaTeX[1] code of the expression using MathJax[2]. For instance, for the SymPy expression of 1/21/2, the LaTeX\LaTeX code and the rendering by Mathjax is as follows:

sympy_expr = S("1/2")
print("LaTeX code:", sympy_expr._repr_latex_())
S("1/2")

For this lab, you will see how arbitrary precision arithmetic can be carried out using symbols.

Symbolic Hypotenuse Calculator

We can define the following function to calculate the length c of the hypotenuse when given the lengths a and b of the other sides:

1
2
3
def length_of_hypotenuse(a, b):
    c = (a**2 + b**2) ** S("1/2")
    return c

Program 1:A function that computes the length of hypotenuse

def length_of_hypotenuse(a, b):
    # YOUR CODE HERE
    raise NotImplementedError
    return c

You can check your code against a few cases listed in the test cell below.

# tests
assert length_of_hypotenuse(0, 0) == 0
assert length_of_hypotenuse(3, 4) == 5
assert length_of_hypotenuse(4, 7) == sqrt(65)

The tests use == instead of isclose because the compution should be exact. For instance, the hypotenuse of the last test case is:

length_of_hypotenuse(4, 7)
# hidden tests

If you are curious about the hidden test, it is like this:

1
2
a, b = symbols('a, b', nonnegative=True)
assert length_of_hypotenuse(a, b) == sqrt(a**2 + b**2)

Program 2:Test of the exact formula of the length of hypotenuse

The first line assign the variables a and b to the symbols Symbol('a') and Symbol('b') respectively, both of which are assumed to be nonnegative.

a, b = symbols('a, b', nonnegative=True)
a, a.is_nonnegative, 0<=a<oo, sqrt(a).is_real, a<0, a>0

Assumptions can affect the check for equivalence ==:

a_ = Symbol('a')
sqrt(abs(a_)**2) == a_, sqrt(abs(a) ** 2) == a

In other words,

  • a2≢a\sqrt{\lvert a\rvert^2} \not\equiv a in general, but
  • a2=aa0.\sqrt{\lvert a\rvert^2} = a \qquad \forall a\geq 0.

There is a further subtlety that, in Mathematics, equality Eq is different from equivalence ==:

Eq(sqrt(abs(a_)**2), a_), Eq(sqrt(abs(a) ** 2), a)

In the first case, the equality a2=a\sqrt{\lvert a \rvert^2} = a

  • neither simplifies to True, as a_ may be negative,
  • nor simplifies to False, as a_ may be non-negative.

In the second case, the equality holds True as a is non-negative.

Similarly, symbols with the same name but different assumptions may be equal but are not equivalent:

Eq(a, a_), a == a_, a == Symbol('a', nonnegative=True)

Calculus

Can we do complicated arithmetics with python. What about Calculus?

tan(x)dx=?\int \tan(x)\, dx = \color{red}{?}

Try SymPy Gamma or SymPy Beta:

  • Take a look at the different panels to learn about the solution: Steps, Plot, and Derivative.
  • Try different random examples.

While web applications like SymPy Gamma or Beta offer a user-friendly and convenient interface for performing symbolic computations quickly without needing to install anything, using SymPy within a Python program provides significantly greater flexibility and control.

To compute the integration in Python, we first define a symbolic variable x:

x = Symbol("x")

The SymPy expression for tan(x)\tan(x) is:

f = tan(x)
f

To compute the integration:

f(x)dx\int f(x) dx
c = Symbol("c")
g = integrate(f) + c  # c is assumed to be constant with respect to x
g

To compute the derivative:

ddxg(x)\frac{d}{dx}g(x)
diff_g = diff(g, x)
diff_g

The answer can be simplified as expected:

simplify(diff_g)
g.subs(c, 0)

To plot the functions:

p = plot(f, g.subs(c, 0), (x, -2 * pi / 5, 2 * pi / 5), ylabel="y", legend=True)
# YOUR CODE HERE
raise NotImplementedError

The following test should plot your expression f in SymPy.

# tests
assert simplify(f.subs(x, 0) - 1) == 0
assert simplify(f.subs(x, S(1)/2) - sqrt(3)*2/3) == 0
# hidden tests
Footnotes
  1. LaTeX is a high-level typesetting system for creating structured documents with complex formatting for Mathematics as well. It is built on top of the TeX\TeX typesetting system originally developed by Donald Knuth, with LaTeX itself created by Leslie Lamport.

  2. MathJax is a JavaScript library for displaying LaTeX, MathML, and AsciiMath notation in web browsers.