C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 helpful. If some parts of the program use these methods, others 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
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.
ErrorHere: 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
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
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
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, CubePython 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
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.
MemoizePython program 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
Python program 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