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 |
no | |
x-y |
no | |
x*y |
no | |
x/y |
no | |
x//y |
no | |
remainder of |
x%y |
no |
x**y |
no | |
abs(x) |
no | |
log(x) |
yes | |
log(b,a) |
yes | |
E |
yes | |
pi |
yes | |
sin(x) |
yes | |
asin(x) |
yes | |
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)
If you want a decimal approximation instead, you can use the N
function.
1
N(sqrt(2))
Or you can use the evalf
function.
1
sqrt(2).evalf()
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
1
Rational(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)