[Edu-sig] Python and pre-Calculus
kirby urner
kirby.urner at gmail.com
Sun Sep 10 16:27:23 CEST 2006
On 9/8/06, kirby urner <kirby.urner at gmail.com> wrote:
> And definitely use generators. The fibonacci sequence is a fantastic
> place to begin, even if your school is a "no da vinci code" zone, sort
> of the way mine is (we got sick of it after a whole year of hype).
Per convergent generators, here's one for cosine:
def cosgen(x):
"""
convergent summation to cosine(x)
factorial defined off camera
"""
thesum = 0
n = 0
sign = 1
while True:
thesum += (sign * pow(x, 2*n)) / fact(2*n)
yield thesum
n += 1
sign = -sign
>>> from math import cos
>>> target = cos(14.21)
>>> target
-0.072768683554320104
>>> thegen = cosgen(14.21)
>>> while abs(target - thegen.next())>0.000001: pass
>>> thegen.next()
-0.072768693540998033
Now this is a little bit dangerous, but if you're certain of
convergence and want to catch when the floating point value is no
longer changing, you can get away with:
>>> while (thegen.next() <> thegen.next()): pass
>>> thegen.next()
-0.072768683575483162
>>> target
-0.072768683554320104
So we notice some disagreement here.
What if we go to more precision?
def cosgen(x):
thesum = Decimal(0)
n = Decimal(0)
sign = Decimal(1)
two = Decimal(2)
while True:
thesum += (sign * pow(x,two*n))/fact(two*n)
yield thesum
n += 1
sign = -sign
>>> from decimal import *
>>> getcontext().prec = 30
>>> var = Decimal(14.21)
>>> thegen = cosgen(var)
>>> thegen.next()
Decimal("1")
>>> while (thegen.next() <> thegen.next()): pass
>>> thegen.next()
Decimal("-0.0727686835543192487699552024271")
>>> target
-0.072768683554320104
Still a disrepancy, but I'm thinking the generator is now more
precise. Let's push out further:
>>> getcontext().prec = 100
>>> thegen = cosgen(var)
>>> while (thegen.next() <> thegen.next()): pass
>>> thegen.next()
Decimal("-0.07276868355431924876995437627048855025971011082339833272762148823931248781362040259253050759451593338")
OK, so it looks like math.cosine is only accurate up to
-0.0727686835543 then rounding error.
Kirby
More information about the Edu-sig
mailing list