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:

import numpy as np 
nums = np.random.randn(10, 4)
print("Original arrays:")
print(nums)
print("Set the array values with specified precision:")
np.set_printoptions(precision=4)
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]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]