random Decimal in python

后端 未结 7 1156
野趣味
野趣味 2020-12-31 08:24

How do I get a random decimal.Decimal instance? It appears that the random module only returns floats which are a pita to convert to Decimals.

相关标签:
7条回答
  • 2020-12-31 09:03

    The random module has more to offer than "only returning floats", but anyway:

    from random import random
    from decimal import Decimal
    randdecimal = lambda: Decimal("%f" % random.random())
    

    Or did I miss something obvious in your question ?

    0 讨论(0)
  • 2020-12-31 09:05

    From the standard library reference :

    To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error).

    >>> import random, decimal
    >>> decimal.Decimal(str(random.random()))
    Decimal('0.467474014342')
    

    Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.

    0 讨论(0)
  • 2020-12-31 09:09
    import random
    y = eval(input("Enter the value of y for the range of random number : "))
    x = round(y*random.random(),2)  #only for 2 round off 
    print(x)
    
    0 讨论(0)
  • 2020-12-31 09:11

    If you know how many digits you want after and before the comma, you can use:

    >>> import decimal
    >>> import random
    >>> def gen_random_decimal(i,d):
    ...  return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d)))
    
    ...
    >>> gen_random_decimal(9999,999999) #4 digits before, 6 after
    Decimal('4262.786648')
    >>> gen_random_decimal(9999,999999)
    Decimal('8623.79391')
    >>> gen_random_decimal(9999,999999)
    Decimal('7706.492775')
    >>> gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after
    Decimal('35018421976.794013996282')
    >>>
    
    0 讨论(0)
  • 2020-12-31 09:11
    decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
    
    0 讨论(0)
  • 2020-12-31 09:21

    What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.

    You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see randrange here):

    decimal.Decimal(random.randrange(10000))/100
    
    0 讨论(0)
提交回复
热议问题