NumPy can provide various techniques to round the elements of a float array away from zero. Any positive number with a fractional component will be rounded up to the next highest integer, and any negative number with a fractional component will be rounded down to the next lowest integer. In this tutorial, we will explore how to use NumPy to round the elements of a float array away from zero and will see some examples.
1. Using "ceil()" function:
NumPy’s ceil()
function rounds each positive element of array up to the next highest integer.
This function returns the ceiling of each element of the input array, which means that it rounds up each element to the next highest integer.
In the above code, we first import the NumPy library and assign it the alias np
. We create an array by using np.array()
function. We then round off each array element by using np.ceil()
function.
2. Using "where()" and "floor()" function:
- The
numpy.where()
function is used to return an array with elements from one of two input arrays, depending on whether a specified condition is true or false. Thewhere()
function takes three arguments: a boolean condition, a value to be used when the condition is true , and a value to be used when the condition is false. -
floor()
rounds each negative element down to the next lowest integer andceil()
function rounds each positive element of array up to the next highest integer.
In the above code, NumPy module is imported and aliased as np
. After, creating array using np.array()
, np.where()
function is called with three arguments
- The first argument is the condition
arr > 0
, which is a boolean array indicating whether each element inarr
is greater than zero. - The second argument is the value to use where the condition is true. In this case,
np.ceil(arr)
is used, which returns an array of the smallest integers greater than or equal to each element inarr
. - The third argument is the value to use where the condition is false. In this case,
np.floor(arr)
is used, which returns an array of the largest integers less than or equal to each element
3. Using "sign()" function:
You can use sign() and ceil() functions to round the elements of the array away from zero.-
The
sign()
function returns an array of the same shape as array, where each element is the sign of the corresponding element in array: -
-1 for negative values,
-
0 for zero values,
-
1 for positive values.
Let see the example given below:
The code uses the NumPy library and gives it alias to np
. It creates an array and finds the sign of each element using the np.sign()
function. It then takes the absolute value of each element using np.abs()
, and rounds them up to the nearest integer using np.ceil()
. Finally, it multiplies the sign of each element by the rounded-up absolute value to get the final array.
Note: To learn more about, visit the thread, rounding-off array elements.