Eduardo Sampaio Soares - 19 days ago 4

Python Question

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.

Thanks!

Answer

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.

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.

Source (Stackoverflow)

Comments