Python Python Tutorial File Handling NumPy Tutorial NumPy Random NumPy ufunc Pandas Tutorial Pandas Cleaning Data Pandas Correlations Pandas Plotting SciPy Tutorial



NumPy ufunc Rounding Decimals

NumPy is a popular Python library used for scientific computing. It provides a powerful array object and a large collection of mathematical functions to operate on these arrays. One of the functions provided by NumPy is ufunc (universal functions), which are functions that operate element-wise on arrays. In this article, we will discuss NumPy ufunc rounding decimals.

NumPy ufunc rounding decimals is a function that rounds the elements of an array to the nearest integer or to a specified number of decimal places. This function is useful in many scientific and engineering applications where precision is important.

Let's take a look at some examples of how to use NumPy ufunc rounding decimals.

Rounding to the Nearest Integer

To round an array to the nearest integer, we can use the around() function. The around() function takes two arguments: the array to be rounded and the number of decimal places to round to. If the number of decimal places is not specified, the function rounds to the nearest integer.

<pre>
import numpy as np

arr = np.array([1.2, 2.5, 3.7, 4.0, 5.8, 6.1])
print(np.around(arr))
</pre>

The output of this code will be:

<pre>
[1. 3. 4. 4. 6. 6.]
</pre>

As you can see, the elements of the array have been rounded to the nearest integer.

Rounding to a Specified Number of Decimal Places

To round an array to a specified number of decimal places, we can use the around() function with the second argument specifying the number of decimal places to round to.

<pre>
import numpy as np

arr = np.array([1.234, 2.567, 3.789, 4.012, 5.845, 6.178])
print(np.around(arr, decimals=2))
</pre>

The output of this code will be:

<pre>
[1.23 2.57 3.79 4.01 5.85 6.18]
</pre>

As you can see, the elements of the array have been rounded to two decimal places.

Rounding Up and Down

NumPy ufunc rounding decimals also provides functions to round up and down. The ceil() function rounds up to the nearest integer, while the floor() function rounds down to the nearest integer.

<pre>
import numpy as np

arr = np.array([1.2, 2.5, 3.7, 4.0, 5.8, 6.1])
print(np.ceil(arr))
print(np.floor(arr))
</pre>

The output of this code will be:

<pre>
[2. 3. 4. 4. 6. 7.]
[1. 2. 3. 4. 5. 6.]
</pre>

As you can see, the ceil() function has rounded up to the nearest integer, while the floor() function has rounded down to the nearest integer.

Conclusion

NumPy ufunc rounding decimals is a useful function for rounding the elements of an array to the nearest integer or to a specified number of decimal places. It provides functions to round up and down as well. These functions are useful in many scientific and engineering applications where precision is important.

Reference

Activity