Sometimes, there’s a need to round off our floating point values in our array as the values are maybe quite large or hard to be dealt with. To deal with this problem, there are several methods available in NumPy, which are mentioned below:
1. Using "np.around()":
This function rounds the values in the array to the given number of decimals. The default number of decimals is 0
.
- The code imports the NumPy library and creates a NumPy array called
a
. - Then, the
np.around()
function is applied to round the elements ofa
to2
decimal places, and the result is stored in a new array calledb
. - Finally, the output is displayed by printing
b
.
2. Using "np.floor()":
The np.floor()
function in NumPy returns the floor of the input array, which is the largest integer less than or equal to each element in the array. Here, the function:
- Imports the NumPy library and creates a NumPy array with three floating-point values
then apply the floor function using thenp.floor()
method. - The resulting array
b
contains the integer part of each of the values ina
. - Finally, the code prints array
b
.
3. Using "np.ceil()":
The np.ceil()
function in NumPy returns the ceiling of the input array, which is the smallest integer that is greater than or equal to each element in the input array. Here:
- The function is applied to a NumPy array containing floating-point values.
- The resulting array
b
contains the smallest integer greater than or equal to each element ina
. - The output is displayed using the
print()
function.
4. Using "np.trunc()":
The np.trunc()
function returns the truncated values of the input array, i.e., it removes the decimal part of the values and returns the integer part of the values as a new array. It does not round off the values but simply truncates them toward zero. For example, truncating the value 1.234 will result in 1.0.