Eduardo Sampaio Soares Eduardo Sampaio Soares - 1 year ago 99
Python Question

How to generate random number with a large number of decimals in Python?

How it's going?

I need to generate a random number with a large number of decimal to use in advanced calculation.

I've tried to use this code:

round(random.uniform(min_time, max_time), 1)

But it doesn't work for length of decimals above 15.

If I use, for e.g:

round(random.uniform(0, 0.5), 100)

It returns 0.586422176354875, but I need a code that returns a number with 100 decimals.

Can you help me?


Answer Source

100 decimals

The first problem is how to create a number with 1000 decimals at all.

This won't do:

>>> 1.23456789012345678901234567890

Those are floating point numbers which have limitations far from 100 decimals.

Luckily, in Python, there is the decimal built-in module which can help:

>>> from decimal import Decimal
>>> Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')

Decimal can have any precision you need and it won't introduce floating point errors, but it will be much slower.


Now you just have to create a string with 100 decmals and give it to Decimal.

This will create one random digit:


This will create 100 random digits and concatenate them:

''.join(random.choice('0123456789') for i in range(100))

Now just create a Decimal:

Decimal('0.' + ''.join(random.choice('0123456789') for i in range(100)))

This creates a number between 0 and 1. Multiply it or divide to get a different range.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download