calcuale ----OverflowError: long int too large to convert to float
<pre><code>en_1 = 1
n = 1
factorial = 1
invfactorial = 1
    while en_1 &gt; 1e-6 :
        en = en_1 +invfactorial
        n = n + 1
        factorial = factorial * n
        invfactorial = float(1.0/factorial)
        en_1 = en 
print "e = %.5f"%en
</code></pre>

<p>I want to calculate e via this code, but it cannot work. </p>

<p><code>en_1 &gt; 1e-6</code> will never evaluate to <code>True</code>.  <code>en_1</code> just gets bigger and bigger.  At some point you end up with numbers so large that Python can't handle the conversions.  Instead compare to <code>invfactorial &gt; 1e-6</code>:</p>

<pre><code>en_1 = 1
n = 1
factorial = 1
invfactorial = 1
while invfactorial &gt; 1e-6:  # changed comparison
    en = en_1 +invfactorial
    n = n + 1
    factorial = factorial * n
    invfactorial = float(1.0/factorial)
    en_1 = en # don't need both en_1 and en
</code></pre>

<p>This could be made much simpler:</p>

<pre><code>e = n = fac = 1
while 1.0/fac &gt; 1e-6:
    fac *= n
    e += 1.0/fac
    n += 1
</code></pre>

python python-2.7