[Edu-sig] Where mathematics comes from

Kirby Urner urnerk@qwest.net
Sun, 26 Jan 2003 14:21:35 -0800


At 01:28 PM 1/26/2003 -0800, I wrote:


>One thing we can do in Python is produce successive factorials using a
>generator, because once we have 4!, why go back and start the multiplications
>all over just to get 5!.  Just multiply 4! (which we already have) by
>5 fer gosh sakes.

Of course this argument applies equally well to the fact that we're
going x^0, x^1, x^2.... x^n, i.e. we should just hold on to the last
powering of x and multiply by x once again.  No reason to start over.

This suggests a more specialized generator, which does the whole term,
in e^x's expansion, not just the factorial part.  Also, we can cause
the generator to stop iterating after t terms, by passing this stop
value as a parameter:

(assuming the same import statements as before):

  >>> def eterms(x,t):
         n=0; result=1
         if n == 0: yield 1   # moved this line out of the loop
         while 1:
           n += 1
           if n > t: return   # stop iterating
           else:
              result *= x/n
              yield result

  >>> def polye2(x,t):
         return reduce(add,[j for j in eterms(x,t)])

  >>> polye2(3.45, 30)   # note I reversed parameter order (I like this better)
  31.500392308747941

  >>> exp(3.45)
  31.500392308747937

  >>> polye2(1j*pi, 100)           # again, *really really close* to -1
  (-1+3.3357107625719758e-016j)


Kirby