Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Random number generator upto 2 decimal places using Python

How do I generate random numbers upto 2 decimal places? I am using random.rand but it goes upto 8 decimal places.

import numpy as np
Pe = np.random.rand(5,5)

The current output is

array([[0.53084542, 0.39162757, 0.08501123, 0.00391447, 0.83859363],
       [0.16194795, 0.06216611, 0.96712453, 0.01319061, 0.19207092],
       [0.90371594, 0.80225188, 0.87797408, 0.71086006, 0.2258896 ],
       [0.33869247, 0.16054   , 0.85156147, 0.25426089, 0.87377881],
       [0.79342404, 0.08150748, 0.62888488, 0.43499343, 0.98077841]])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I see two options:

generate floats and round to the wanted decimal places:

D = 2
np.random.rand(5,5).round(D)

or use integers and divide:

D = 2
np.random.randint(10**D, size=(5,5))/10**D

example output:

array([[0.21, 0.6 , 0.75, 0.64, 0.6 ],
       [0.3 , 0.73, 0.95, 0.43, 0.78],
       [0.06, 0.84, 0.19, 0.4 , 0.3 ],
       [0.08, 0.9 , 0.37, 0.53, 0.49],
       [0.13, 0.21, 0.08, 0.51, 0.26]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading