1

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?

Thanks!

1 Answers1

1

100 decimals

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

This won't do:

>>> 1.23456789012345678901234567890
1.2345678901234567

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('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')

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

random

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

This will create one random digit:

random.choice('0123456789')

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.

Community
  • 1
  • 1
zvone
  • 18,045
  • 3
  • 49
  • 77
  • When I multiply it or divide the Decimal number created, the number of decimals is missed and it returns a number with only 15 decimals... Is that normal? What can I do? – Eduardo Sampaio Soares Oct 08 '16 at 23:41
  • @EduardoSampaioSoares You should configure [`decimal.Context`](https://docs.python.org/2/library/decimal.html#context-objects) to have higher precision. E.g. do the calculation within block `with decimal.localcontext(decimal.Context(prec=100)):` – zvone Oct 08 '16 at 23:53
  • You've helped me a lot! Thank you again! – Eduardo Sampaio Soares Oct 09 '16 at 00:13