Python provides a variety of mathematical functions to handle numerical operations. Two such functions, math.trunc()
and math.floor()
, may seem similar at first glance, but they serve distinct purposes when rounding numbers. Both functions accept a single argument, x
, which can be either a floating-point number or an integer. They both return an integer value, making them versatile tools in numerical computations. In this Answer, we’ll study these functions and explore when to use them.
math.trunc()
functionThe math.trunc()
function is used to truncate a number, effectively removing the decimal part without performing any rounding. It essentially rounds toward zero, giving us the integer portion of a number.
import mathx = 3.8y = -2.3result_x = math.trunc(x) # Output: 3result_y = math.trunc(y) # Output: -2print(result_x)print(result_y)
math.floor()
functionOn the other hand, math.floor()
returns the largest integer that is less than or equal to a given number. It always rounds down, even for negative numbers.
import mathx = 3.8y = -2.3result_x = math.floor(x) # Output: 3result_y = math.floor(y) # Output: -3print(result_x)print(result_y)
The key distinction between these functions lies in how they handle negative numbers. While math.floor()
consistently rounds down (towards negative infinity), math.trunc()
effectively truncates towards zero. Let's look at the key difference between these two with the help of an illustration:
Let's understand this with the help of coding examples:
import mathx = -0.2result_floor = math.floor(x) # Output: -1result_trunc = math.trunc(x) # Output: 0print("Result of floor:", result_floor)print("Result of trunc:", result_trunc)
In this case, math.floor()
yields math.trunc()
simply truncates towards zero, giving
Choosing between math.trunc()
and math.floor()
depends on our specific use case. If we need to ensure that the result is always rounded down, even for negative numbers, math.floor()
is the appropriate choice. Conversely, if we want to truncate towards zero, we’ll use math.trunc()
.
In summary, math.trunc()
and math.floor()
are valuable tools for handling numerical operations in Python. Understanding their behavior, particularly when dealing with negative numbers, empowers us to make informed decisions in our code. By leveraging these functions effectively, we can achieve precise and accurate results in our mathematical computations.
Free Resources