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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Yet another way to make a random decimal.
On this example,
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).
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.
The random module has more to offer than "only returning floats", but anyway:
Or did I miss something obvious in your question ?
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):