[파이썬][numpy] numpy `round` 함수

Numpy is a powerful library in Python that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. One such useful function is round, which allows for precise number rounding in Python.

The round function in numpy

The round function in numpy is used to round the elements of an array to the specified number of decimals. It follows the common rounding conventions, where a number halfway between two others is rounded to the nearest even number.

The syntax of the round function is as follows:

numpy.round(arr, decimals=0, out=None)

Examples

Let’s take a look at some examples to better understand how to use the round function in numpy:

Example 1: Rounding to the nearest whole number

import numpy as np

arr = np.array([1.2, 2.5, 3.7, 4.0, 5.9])

rounded_arr = np.round(arr)

print(rounded_arr)

Output:

[1. 2. 4. 4. 6.]

In this example, all the elements of the array arr have been rounded to the nearest whole number using the round function.

Example 2: Rounding to a specified number of decimals

import numpy as np

arr = np.array([1.234, 2.567, 3.789])

rounded_arr = np.round(arr, decimals=2)

print(rounded_arr)

Output:

[1.23 2.57 3.79]

In this example, the elements of the array arr have been rounded to two decimal places using the round function.

Conclusion

The round function in numpy provides a convenient way to round the elements of an array to the desired number of decimals. Whether you need to round to the nearest whole number or to a specific number of decimals, numpy’s round function is a handy tool to achieve precision in your numerical calculations.

Remember to import the numpy library and use the round function with the correct syntax to make the most of this powerful rounding function in your Python code.