() is a function in the NumPy library that is used to round arrays or individual numeric values. This function returns an array or value of the same type as the input and can specify the number of reserved decimal places with optional parameters.
1. Syntax of () function
(a, decimals=0, out=None)
- Parameter description
a
: an array or a single value to be rounded. -
decimals
: Optional parameter, specify the number of reserved decimal places, default is 0. -
out
: Optional parameters, no manual specification is required. Return Value Returns an array or value of the same type as the input.
2. Example of () function
2.1 Rounding a single value
import numpy as np # Round the valuesnumber = 3.14159 rounded_number = (number) print(rounded_number) # Output: 3.0
In the above example, we first importnumpy
library, and defines anumber
The value of the variable is 3.14159. Then, we use()
Function pairnumber
Perform rounding operation and assign the result torounded_number
variable. Finally, we useprint()
Function outputrounded_number
The value of , the result is 3.0.
2.2 Round the array
import numpy as np # Round the arrayarr = ([1.1, 2.6, 3.3, 4.8, 5.5]) rounded_arr = (arr) print(rounded_arr) # Output: [1. 3. 3. 5. 6.]
In the above example, we define a name calledarr
an array containing several floating point elements. Then, we use()
Function pairarr
Perform rounding operation and assign the result torounded_arr
variable. Finally, we useprint()
Function outputrounded_arr
The value of[1. 3. 3. 5. 6.]
。
2.3 Specify the number of reserved decimal places
import numpy as np # Specify keeping 2 decimal placesarr = ([1.123, 2.456, 3.789]) rounded_arr = (arr, decimals=2) print(rounded_arr) # Output: [1.12 2.46 3.79]
In the above example, we use()
Functions to arraysarr
Perform rounding operation and passdecimals
The parameter specifies that two decimal places are retained. Finally, we useprint()
Function outputrounded_arr
The value of[1.12 2.46 3.79]
。
2.4 Assign the result to the specified output array
import numpy as np # Assign the result to the specified output arrayarr = ([1.1, 2.6, 3.3, 4.8, 5.5]) out_arr = np.zeros_like(arr) (arr, out=out_arr) print(out_arr) # Output: [1. 3. 3. 5. 6.]
In the above example, we first create aarr
All-zero array with the same shapeout_arr
. Then, we use()
Function pairarr
Perform rounding operation and assign the result toout_arr
Array. Finally, we useprint()
Function outputout_arr
The value of , the result is the same as in the previous example.
This is all about this article about python() function. For more related python() function content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!