w3resource

NumPy: Set the array values with specified precision

NumPy: Array Object Exercise-198 with Solution

Write a NumPy program to create a 10x4 array filled with random floating point number values with and set the array values with specified precision.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Generating a random 10x4 array
nums = np.random.randn(10, 4)

# Displaying the original array
print("Original arrays:")
print(nums)

# Setting the precision of the array to a specific value (4 decimal places)
np.set_printoptions(precision=4)

# Displaying the array with the specified precision
print("Set the array values with specified precision:")
print(nums)

Sample Output:

Original arrays:
[[-1.23335604  0.54368124  1.93500931 -0.45001639]
 [ 1.20528013  2.04423279 -0.68858903 -0.46642789]
 [ 1.29030601  0.60914425  0.03139104 -1.72528221]
 [-0.32607231 -2.36951679 -0.80374203 -0.26212641]
 [-0.16426628 -0.21524949 -0.35957311 -2.27709735]
 [-0.28851276 -0.59101441  0.22293919 -0.50128832]
 [ 1.3577567   0.05529019  0.81208832  0.70810424]
 [ 0.46853801 -0.81857981  0.80443323  0.52391606]
 [-0.29149088 -0.91153449 -1.00515549  0.31065165]
 [ 2.68952752  1.86676839  1.49239198 -1.0409156 ]]
Set the array values with specified precision:
[[-1.2334  0.5437  1.935  -0.45  ]
 [ 1.2053  2.0442 -0.6886 -0.4664]
 [ 1.2903  0.6091  0.0314 -1.7253]
 [-0.3261 -2.3695 -0.8037 -0.2621]
 [-0.1643 -0.2152 -0.3596 -2.2771]
 [-0.2885 -0.591   0.2229 -0.5013]
 [ 1.3578  0.0553  0.8121  0.7081]
 [ 0.4685 -0.8186  0.8044  0.5239]
 [-0.2915 -0.9115 -1.0052  0.3107]
 [ 2.6895  1.8668  1.4924 -1.0409]]

Explanation:

In the above exercise -

nums = np.random.randn(10, 4): This code generates a 10x4 array with random numbers drawn from a standard normal distribution. The np.random.randn() function takes the shape of the output array as its arguments.

np.set_printoptions(precision=4): This code sets the global print options for NumPy. In this case, the precision parameter is set to 4, which means that when NumPy arrays are printed, their elements will be displayed with 4 decimal places.

print(nums): Finally print() function prints the generated 10x4 array with the specified precision (4 decimal places).

Python-Numpy Code Editor:

Previous: Write a NumPy program to create to concatenate two given arrays of shape (2, 2) and (2,1).
Next: Write a NumPy program to create an array using scientific notation numbers. Set the precision value to 6 and print the array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.