TheDeveloperBlog.com


Python Math Examples

Math. Many math methods are available. And with the math module, we access even more. Abs computes absolute values. Sqrt computes square roots.


Others (cos and sin) are trigonometric. When possible, these built-in methods are preferred over custom code. They are tested. They are reliable.


Abs built-in. A common math method is abs. This computes absolute values. It removes the negative sign (if there is one) from the number and returns that.

Note: When computing a hash code (a number based on data and used for lookup) we sometimes end up with a negative value. Abs fixes that.

Tip: The abs method is not part of the math module. Instead, you can use it directly in your programs.

Based on:

Python 3

Python program that uses abs

# Negative number.
n = -100.5

# Absolute value.
print(abs(n))

Output

100.5

Floor, ceil. Two 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: This rounds the number up to the next highest one. A ceiling is always above us.

Tip: When using methods like floor and ceil, consistency is key. If some parts of the program use these methods, other parts should too.

Python program that imports math

import math

# Fractional number.
n = 100.7

# Absolute value.
print(math.floor(n))
print(math.ceil(n))

Output

100
101

Round. This receives one or two arguments. The second argument tells how many numbers past the decimal point to keep. The final number is rounded up if the next digit is 5 or more.

Python program that uses round

number = 1.23456
print(round(number))
print(round(number, 0))
print(round(number, 1))
print(round(number, 2))
print(round(number, 3))

Output

1        0 digits
1.0      0 digits
1.2      1 digit
1.23     2 digits
1.235    3 digits, last one rounded up to 5

Sum, 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.

Tip: Sum and fsum can be used on any iterable collection. This includes the list, tuple and set.

Caution: If the iterable contains a non-numeric value, a TypeError will occur. We handle this in an except statement.

Try

Here: In this example, the sum() method causes a rounding error to occur. The fsum() method returns a better sum.

Python program that uses sum, fsum

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)

Output

6.999999900000001
6.9999999

Truncate. Truncating a number removes everything past the decimal place. This does not round the number. Instead it just eliminates the fractional part.

Note: A positive number becomes smaller with trunc. And a negative number becomes larger.

Python program that uses math.trunc

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)

Output

123
345

Pow built-in. Exponentiation multiplies a number by itself a certain number of times. With math.pow we apply this operation. Math.pow is similar to the ** operator.

But: When math.pow is applied, the result is always converted to a float. This is not the case with the ** operator.

Tip: More examples of using the exponent operator are available on the numbers page.

Numbers: Square, Cube
Python program that uses math.pow

import math

# Use math.pow method.
a = math.pow(2, 3)

# Use operator.
b = 2 ** 3

# Print results.
print(a)
print(b)

Output

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).

Tip: If your program often uses square roots, a cache or lookup table may be helpful. You could memoize the result of math.sqrt for speed.

Memoize
Python that uses math.sqrt

import math

value1 = 9
value2 = 16
value3 = 100

# Use sqrt method.
print(math.sqrt(value1))
print(math.sqrt(value2))
print(math.sqrt(value3))

Output

3.0
4.0
10.0

Pi, E. 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.

Python that uses math.e, pi

import math

# This returns the value of e.
print(math.e)

# And this is pi.
print(math.pi)

Output

2.718281828459045
3.141592653589793

Abs performance. Are math methods fast? In this program, I tested the abs method versus a simple if-else statement that also computes absolute values.

Info: They compute absolute values of the number a. In the results, doing an if-else statement to compute the absolute value was faster.

But: The difference here is not relevant to many programs. I recommend using abs() for clearer programs.

Python that benchmarks abs

import time

print(time.time())

# Compute absolute value with abs.
a = -1
i = 0
while i < 10000000:
    b = abs(a)
    i += 1

print(time.time())

# Compute absolute value with if-statement.
a = -1
i = 0
while i < 10000000:
    if a < 0:
        b = -a
    else:
        b = a
    i += 1

print(time.time())

Output

1346355970.511
1346355973.081 (Abs = 2.57  s)
1346355975.509 (If  = 2.428 s)

Compound interest. Math is used in the real world. Please also check out the compound_interest Python implementation. It uses pow to compute an exponential function.

Compound Interest

Math is everywhere. It is possible to directly compute mathematical functions. We could add methods that use arithmetic operators. But this adds complexity. It bloats programs.


Instead, we can use built-ins. These are found in the default and math modules. This approach is more effective. It is simpler. It makes programs easier to understand and maintain.