Question:

In Python(programming) how do you generate random decimals?

by  |  earlier

0 LIKES UnLike

I know about randint but that only generates whole numbers and I would like to be able to generate numbers with 2 decimal places.

 Tags:

   Report

3 ANSWERS


  1. Generate a random int between 0 and 100 (for two decimal places) times the number you want and then divide by 100

    eg:

    >>> from random import randint

    >>> def randomDecimal(a, b):

    ...........return randint(int(a), int(100 * b)) / 100.0

    >>> randomDecimal(7, 49)

    13.65

    >>>

    or you can use the random method to return a random floating point number between 0 and 1.

    >>> import random

    >>> random.random()

    0.013448514990953231

    >>>  


  2. If you need a random number between 1 and 10 you can simple compute a random number from 100 to 999 and divide the result by 100 which will give you a number with 2 decimals.

  3. You should use numpy or scipy: http://numpy.scipy.org/ or http://www.scipy.org/

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.