nth root

Mensanator mensanator at aol.com
Sat Jan 31 12:18:53 EST 2009


On Jan 31, 10:53 am, Mensanator <mensana... at aol.com> wrote:
> On Jan 31, 8:05 am, Mark Dickinson <dicki... at gmail.com> wrote:
>
> > On Jan 31, 1:23 pm, Steve Holden <st... at holdenweb.com> wrote:
>
> > > Much more significant points, given the limited precision of the doubles
> > > Python will be using. Could gmpy do this better, I wonder?
>
> > Almost certainly, if exact results are wanted!  At least, GMP has
> > an mpz_root function; I don't know offhand whether gmpy makes it
> > accessible from Python.
>
> > Mark
>
> What am I doing wrong here?
>
> IDLE 2.6b1
>
> >>> import timeit
> >>> from gmpy import root
> >>> root(4021503534212915433093809093996098953996019232,13)
> (mpz(3221), 0)
> >>> t1 = timeit.Timer("x = root(a,r)", "a = 4021503534212915433093809093996098953996019232; r = 13")
> >>> t1.timeit()
>
> Traceback (most recent call last):
>   File "<pyshell#5>", line 1, in <module>
>     t1.timeit()
>   File "C:\Python26\lib\timeit.py", line 193, in timeit
>     timing = self.inner(it, self.timer)
>   File "<timeit-src>", line 6, in inner
> NameError: global name 'root' is not defined

Never mind, I figured it out.

>>> import gmpy
>>> a=gmpy.mpz(4021503534212915433093809093996098953996019232)
>>> r=13
>>> t1 = timeit.Timer("x = root(a,r)", "from gmpy import root; from __main__ import a,r")
>>> t1.timeit()
4.7018698921850728

For comparison:

>>> t2 = timeit.Timer("x = n**power", "n = 4021503534212915433093809093996098953996019232.; power = 1./13")
>>> t2.timeit()
0.43993394115364026



More information about the Python-list mailing list