Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Rounding Decimals

In NumPy, you can round decimal numbers using various rounding functions provided by the numpy library. These functions allow you to round numbers to the nearest integer, a specified number of decimal places, or to the nearest multiple of a specified value.


numpy.round(): This function rounds the elements of an array to the nearest integer. If the element is equidistant from two integers, it rounds to the nearest even integer by default. You can specify the number of decimal places to round to using the decimals parameter.

import numpy as np
arr = np.array([1.2, 2.5, 3.7])
# Round to the nearest integer
rounded_arr = np.round(arr)
print(rounded_arr) # Output: [1. 2. 4.]
# Round to one decimal place
rounded_arr_1dp = np.round(arr, decimals=1)
print(rounded_arr_1dp) # Output: [1.2 2.5 3.7]


numpy.floor() :This function rounds the elements of an array down to the nearest integer (towards negative infinity).

import numpy as np
arr = np.array([1.2, 2.5, 3.7])
# Round down to the nearest integer
floored_arr = np.floor(arr)
print(floored_arr) # Output: [1. 2. 3.]


numpy.ceil(): This function rounds the elements of an array up to the nearest integer (towards positive infinity).

import numpy as np
arr = np.array([1.2, 2.5, 3.7])
# Round up to the nearest integer
ceiled_arr = np.ceil(arr)
print(ceiled_arr) # Output: [2. 3. 4.]


numpy.trunc(): This function truncates the decimal part of each element, leaving only the integer part.

import numpy as np
arr = np.array([1.2, 2.5, 3.7])
# Truncate decimal part
truncated_arr = np.trunc(arr)
print(truncated_arr) # Output: [1. 2. 3.]


These rounding functions provide flexibility for various rounding requirements, allowing you to manipulate arrays of decimal numbers according to your needs.






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java