How to do basic mathematical computations (in Python, using SymPy)
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 |
| $x-y$ | x-y |
no |
| $xy$ | x*y |
no |
| $\frac xy$ | x/y |
no |
| $\left\lfloor\frac xy\right\rfloor$ | x//y |
no |
| remainder of $x\div y$ | x%y |
no |
| $x^y$ | x**y |
no |
| $\vert x\vert$ | abs(x) |
no |
| $\ln x$ | log(x) |
yes |
| $\log_a b$ | log(b,a) |
yes |
| $e^x$ | E |
yes |
| $\pi$ | pi |
yes |
| $\sin x$ | sin(x) |
yes |
| $\sin^{-1} x$ | asin(x) |
yes |
| $\sqrt 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)
$\displaystyle \sqrt{2}$
If you want a decimal approximation instead, you can use the N function.
1
N(sqrt(2))
$\displaystyle 1.4142135623731$
Or you can use the evalf function.
1
sqrt(2).evalf()
$\displaystyle 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
$\displaystyle 0.333333333333333$
1
Rational(1,3)
$\displaystyle \frac{1}{3}$
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)