How to generate random number with a large number of decimals in Python?
<p>How it's going?</p>

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

<p>I've tried to use this code:</p>

<pre><code>round(random.uniform(min_time, max_time), 1)
</code></pre>

<p>But it doesn't work for length of decimals above 15.</p>

<p>If I use, for e.g:</p>

<pre><code>round(random.uniform(0, 0.5), 100)
</code></pre>

<p>It returns 0.586422176354875, but I need a code that returns a number with 100 decimals. </p>

<p><strong>Can you help me?</strong></p>

<p>Thanks!</p>

<h2>100 decimals</h2>

<p>The first problem is how to create a number with 1000 decimals at all.</p>

<p>This won't do:</p>

<pre><code>&gt;&gt;&gt; 1.23456789012345678901234567890
1.2345678901234567
</code></pre>

<p>Those are floating point numbers which have limitations far from 100 decimals.</p>

<p>Luckily, in Python, there is the <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code> built-in module</a> which can help:</p>

<pre><code>&gt;&gt;&gt; from decimal import Decimal
&gt;&gt;&gt; Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
</code></pre>

<p>Decimal can have any precision you need and it won't introduce <a href="http://stackoverflow.com/q/19473770/389289">floating point errors</a>, but it will be much slower.</p>

<h2>random</h2>

<p>Now you just have to create a string with 100 decmals and give it to <code>Decimal</code>.</p>

<p>This will create one random digit:</p>

<pre><code>random.choice('0123456789')
</code></pre>

<p>This will create 100 random digits and concatenate them:</p>

<pre><code>''.join(random.choice('0123456789') for i in range(100))
</code></pre>

<p>Now just create a <code>Decimal</code>:</p>

<pre><code>Decimal('0.' + ''.join(random.choice('0123456789') for i in range(100)))
</code></pre>

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

python random numbers