Using fractions instead of floats

mensanator at aol.com mensanator at aol.com
Tue Oct 2 00:59:35 EDT 2007


On Oct 1, 8:17?pm, richy... at gmail.com wrote:
> On Oct 1, 9:03 pm, "mensana... at aol.com" <mensana... at aol.com> wrote:
>
> > On Oct 1, 7:20 pm, richy... at gmail.com wrote:
>
> > > On Oct 1, 8:30 am, Nick Craig-Wood <n... at craig-wood.com> wrote:
>
> > > >   >>> mpq(1,3)+0.6
> > > >   mpq(14,15)
>
> > > Golly!  That's quite impressive.  And more than a little bit magic as
> > > well, since 0.6 is definitely not the same as 3/5.  
>
> > It's not? Since when?
>
> The 0.6 above is a floating point number, mathematically very close to
> 0.6 but definitely not equal to it, since 0.6 can't be represented
> exactly as a float.

Oh, you mean something like this, right?

>>> import gmpy
>>> a = 0.6
>>> a
0.59999999999999998

So, the rational should have 59999999999999998
in the neumerator and 100000000000000000 in the
denominator? But it doesn't

>>> b = gmpy.mpq(a)
>>> b
mpq(3,5)

Why do you suppose that is? For that matter, why
does

>>> str(a)
'0.6'

give me an EXACT representation? Didn't you just
say it couldn't be represented exactly?

Which is correct,

>>> str(a)
'0.6'

or

>>> repr(a)
'0.59999999999999998'

?

How does gmpy make the conversion from float to rational?




More information about the Python-list mailing list