NumPy fix()
The numpy.fix()
function rounds each element in an input array to the nearest integer towards zero.
Syntax
</>
Copy
numpy.fix(x, out=None)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like | An array of floating-point values to be rounded towards zero. |
out | ndarray, optional | Optional output array to store the rounded values. If not provided, a new array is created. |
Return Value
Returns an array with the same shape as the input, with values rounded towards zero. The returned array retains the same data type as the input.
Examples
1. Rounding a Single Floating-Point Number
Here, we round a single floating-point number towards zero.
</>
Copy
import numpy as np
# Define a single floating-point number
num = -2.7
# Apply numpy.fix()
result = np.fix(num)
# Print the result
print("Rounded value:", result)
Output:
Rounded value: -2.0

2. Rounding an Array of Floating-Point Numbers
We apply numpy.fix()
to an array containing both positive and negative values.
</>
Copy
import numpy as np
# Define an array of floating-point numbers
arr = np.array([-3.9, -2.5, -1.3, 0.3, 1.8, 2.9, 3.7])
# Apply numpy.fix()
rounded_arr = np.fix(arr)
# Print the result
print("Original array:", arr)
print("Rounded array:", rounded_arr)
Output:
Original array: [-3.9 -2.5 -1.3 0.3 1.8 2.9 3.7]
Rounded array: [-3. -2. -1. 0. 1. 2. 3.]

3. Using the out
Parameter
We use an output array to store the result instead of creating a new array.
</>
Copy
import numpy as np
# Define an array of floating-point numbers
arr = np.array([-4.7, -2.2, 0.8, 2.6, 4.1])
# Create an output array with the same shape
output_array = np.empty_like(arr)
# Apply numpy.fix() with an output parameter
np.fix(arr, out=output_array)
# Print the result
print("Output array:", output_array)
Output:
Output array: [-4. -2. 0. 2. 4.]

The results are stored in output_array
instead of creating a new one.