In Python we discover many built-in mathematical functions. Consider a square root—we just call math.sqrt
. No custom code is required.
We can apply floors and ceilings to reduce, and increase, fractional numbers. With sum()
and fsum
we can add up numbers.
Floor
, ceilTwo common math functions are floor and ceil. Floor
removes the digits past the decimal place. In this example it changes 100.7 to 100.
Ceil()
rounds the number up to the next highest one. A ceiling is always above us.import math # Fractional number. n = 100.7 # Absolute value. print(math.floor(n)) print(math.ceil(n))100 101
fsum
With sum, we add together the elements in a list. Fsum is a more accurate way to sum floating-point numbers. On integers, the methods are equal. But fsum
is better for floats.
fsum
can be used on any iterable
collection. This includes the list, tuple and set.iterable
contains a non-numeric value, a TypeError
will occur. We handle this in an except statement.sum()
method causes a rounding error to occur. The fsum()
method returns a better sum.import math # Input list. values = [0.9999999, 1, 2, 3] # Sum values in list. r = sum(values) print(r) # Sum values with fsum. r = math.fsum(values) print(r)6.999999900000001 6.9999999
Truncating a number removes everything past the decimal place. This does not round the number. Instead it just eliminates the fractional part.
math.trunc
. This is similar to casting to (int
) in C-like languages.import math # Truncate this value. value1 = 123.45 truncate1 = math.trunc(value1) print(truncate1) # Truncate another value. value2 = 345.67 truncate2 = math.trunc(value2) print(truncate2)123 345
Pow
built-inExponentiation multiplies a number by itself a certain number of times. With math.pow
we apply this operation. Math.pow
is similar to the ** operator.
math.pow
is applied, the result is always converted to a float
. This is not the case with the ** operator.import math # Use math.pow method. a = math.pow(2, 3) # Use operator. b = 2 ** 3 # Print results. print(a) print(b)8.0 8
Sqrt
In most programs, we do not need square roots. But when we do, the math.sqrt
method is useful. It receives one argument. It returns the square root (in floating-point form).
math.sqrt
for speed.import math value1 = 9 value2 = 16 value3 = 100 # Use sqrt method. print(math.sqrt(value1)) print(math.sqrt(value2)) print(math.sqrt(value3))3.0 4.0 10.0
You probably know the approximate values of E and pi. And you could specify these directly in a Python program. But with math.e
and math.pi
, we avoid this hassle.
import math # This returns the value of e. print(math.e) # And this is pi. print(math.pi)2.718281828459045 3.141592653589793
It is possible to directly compute mathematical functions. We could add methods that use arithmetic operators. But this adds complexity—it bloats programs.
These are found in the default and math modules. This approach is more effective. It is simpler, and it makes programs easier to understand and maintain.