Float compression [Re: floating point math results question]

François Pinard pinard at iro.umontreal.ca
Sun Jan 27 13:14:47 EST 2002


[About efficient ways to discover given decimal digits of a rational number]

> > I would guess that `str()' has been implemented with some care about
> > efficiency.  Couldn't you just use it?

[Jonathan Hogg]

> However, here you've lost me.

Oh, because I lost myself and you tried to follow me, sorry!  I missed
that you were speaking about _rational_ expressions, and thought you were
speaking about mere floats.  I guess that if I wanted, say, two digits
before point, and three after, for a given rational number, I would write:

   str(int(number * 1000) % 100000)

It might still be an efficient enough approach if one wanted a great deal
of decimals, because Python would internally do most of the work :-).
You cannot escape burning some CPU, anyway...

> Didn't you write the __str__ hook?

Yes, of course.  It yields an "N:M" string, explicitly showing numerator
and denominator of the fraction (possibly preceded by a sign).  A global
option can also trigger "Q:N:M", meaning Q + N:M with N lesser then M.

> Or do you implicitly convert to float and let normal str operate on that?

I presume that "%f" format implicitly calls float(), for which I have a
hook indeed.  But it may fail, as the range of floats is limited.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list