В научных вычислениях и анализе данных часто необходимо округлять числа до целых чисел для различных целей. NumPy, популярная библиотека Python для числовых вычислений, предоставляет несколько методов, позволяющих эффективно и результативно округлять числа. В этой статье мы рассмотрим различные методы округления чисел до целых чисел в NumPy, а также приведем примеры кода для каждого метода.
Методы округления чисел до целых:
- numpy.round():
Функцияround()в NumPy возвращает ближайшее целое число к заданному значению. По умолчанию в случае ничьей оно округляется до ближайшего четного целого числа.
import numpy as np
x = np.array([1.4, 2.7, 3.2, 4.8, 5.5])
rounded_values = np.round(x)
print(rounded_values)
Выход:
[1. 3. 3. 5. 6.]
2. numpy.ceil():
The `ceil()` function returns the smallest integer greater than or equal to a given value.
```python
import numpy as np
x = np.array([1.4, 2.7, 3.2, 4.8, 5.5])
ceiled_values = np.ceil(x)
print(ceiled_values)
Выход:
[2. 3. 4. 5. 6.]
3. numpy.floor():
The `floor()` function returns the largest integer less than or equal to a given value.
```python
import numpy as np
x = np.array([1.4, 2.7, 3.2, 4.8, 5.5])
floored_values = np.floor(x)
print(floored_values)
Выход:
[1. 2. 3. 4. 5.]
4. numpy.rint():
The `rint()` function rounds the elements of an array to the nearest integer, preserving the dtype.
```python
import numpy as np
x = np.array([1.4, 2.7, 3.2, 4.8, 5.5])
rounded_values = np.rint(x)
print(rounded_values)
Выход:
[1. 3. 3. 5. 6.]
5. numpy.trunc():
The `trunc()` function truncates the decimal part of a number and returns the integer.
```python
import numpy as np
x = np.array([1.4, 2.7, 3.2, 4.8, 5.5])
truncated_values = np.trunc(x)
print(truncated_values)
Выход: