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
# Input list.
values = [0.9999999, 1, 2, 3]
# Sum values in list.
r = sum(values)
# Sum values with fsum.
r = math.fsum(values)
Truncate. Truncating a number removes everything past the decimal place. This does not round the number. Instead it just eliminates the fractional part.
Note: The number before the decimal place is never changed with math.trunc. This is similar to casting to (int) in C-like languages.
Python program that uses math.trunc
# Truncate this value.
value1 = 123.45
truncate1 = math.trunc(value1)
# Truncate another value.
value2 = 345.67
truncate2 = math.trunc(value2)
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.