Trouble getting loop to break
davisn90210 at gmail.com
davisn90210 at gmail.com
Tue Nov 20 13:42:48 EST 2007
Instead of comparing sum to the "known" value of e**x, why not test
for convergence? I.e., if sum == last_sum: break. Seems like that
would be more robust (you don't need to know the answer to computer
the answer), since it seems like it should converge.
--Nathan Davis
On Nov 20, 1:41 am, Dick Moores <r... at rcblue.com> wrote:
> I'm writing a demo of the infinite series
>
> x**0/0! + x**1/1! + x**2/2! + x**3/3! + ... = e**x (x is non-negative)
>
> It works OK for many x, but for many the loop doesn't break. Is there
> a way to get it to break where I want it to, i.e., when the sum
> equals the limit as closely as the precision allows?
>
> Here's what I have:
>
> ======= series_xToN_OverFactorialN.py ==========================
> #!/usr/bin/env python
> #coding=utf-8
> # series_xToN_OverFactorialN.py limit is e**x from p.63 in The
> Pleasures of Pi,e
> from mpmath import mpf, e, exp, factorial
> import math
> import time
> precision = 100
> mpf.dps = precision
> n = mpf(0)
> x = mpf(raw_input("Enter a non-negative int or float: "))
> term = 1
> sum = 0
> limit = e**x
> k = 0
> while True:
> k += 1
> term = x**n/factorial(n)
> sum += term
> print " sum = %s k = %d" % (sum, k)
> print "exp(%s) = %s" % (x, exp(x))
> print " e**%s = %s" % (x, e**x)
> print
> if sum >= limit:
> print "math.e**%s = %f" % (x, math.e**x)
> print "last term = %s" % term
> break
> time.sleep(0.2)
> n += 1
>
> """
> Output for x == mpf(123.45):
> sum =
> 410822093109668964239148908443317876138879647013995774.2951431466270782257597573259486687336246984942
> k = 427
> exp(123.45) =
> 410822093109668964239148908443317876138879647013995774.2951431466270782257597573259486687336246984942
> e**123.45 =
> 410822093109668964239148908443317876138879647013995774.2951431466270782257597573259486687336246984942
> """
> ====================================================
>
> This is also on the web at <http://python.pastebin.com/f1a5b9e03>.
>
> Examples of problem x's: 10, 20, 30, 40, 100, 101
> Examples of OK x's: 0.2, 5, 10.1, 11, 33.3, 123.45
>
> Thanks,
>
> Dick Moores
More information about the Python-list
mailing list