How to do basic mathematical computations (in Python)
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
For those expressions that need the Python math package, use the code
import math
beforehand to ensure that package is loaded. Alternatively,
you can write from math import *
and thus drop the math
prefixes in
the table below.
Mathematical notation | Python code | Requires math package? |
---|---|---|
$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$ | math.log(x) |
yes |
$\log_a b$ | math.log(b,a) |
yes |
$e^x$ | math.exp(x) |
yes |
$\pi$ | math.pi |
yes |
$\sin x$ | math.sin(x) |
yes |
$\sin^{-1} x$ | math.asin(x) |
yes |
$\sqrt x$ | x**0.5 |
no |
$\sqrt x$ | math.sqrt(x) |
yes |
Other trigonometric functions are also available besides just math.sin
,
including math.cos
, math.tan
, etc.
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)