Link Search Menu Expand Document (external link)

How to do basic mathematical computations (in Python, using SymPy)

See all solutions.

Task

How do we write the most common mathematical operations in a given piece of software? For example, how do we write multiplication, or exponentiation, or logarithms, in Python vs. R vs. Excel, and so on?

Solution

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output
Mathematical notation Python code Requires SymPy?
x+y x+y no
xy x-y no
xy x*y no
xy x/y no
xy x//y no
remainder of x÷y x%y no
xy x**y no
|x| abs(x) no
lnx log(x) yes
logab log(b,a) yes
ex E yes
π pi yes
sinx sin(x) yes
sin1x asin(x) yes
x sqrt(x) yes

Other trigonometric functions are also available besides just sin, including cos, tan, etc.

Note that SymPy gives precise answers to mathematical queries, which may not be what you want.

1
sqrt(2)

2

If you want a decimal approximation instead, you can use the N function.

1
N(sqrt(2))

1.4142135623731

Or you can use the evalf function.

1
sqrt(2).evalf()

1.4142135623731

By contrast, if you need an exact rational number when Python gives you an approximation, you can use the Rational function to build one. Note the differences below:

1
1/3

0.333333333333333

1
Rational(1,3)

13

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)