number comparison problem
Chris Fonnesbeck
spam at fisher.forestry.uga.edu
Thu Oct 17 08:36:45 EDT 2002
It does help. I am using python for scientific computing
(statistical), doing optimization routines such as the golden section
search, etc. In fact, I have been using abs(a-b)<eps in such routines
as a way of moving from coarse- to fine-grain optimization methods,
but I did not think I would have to use this for ALL floating point
calculations.
Thanks
cjf
"Mark McEahern" <marklists at mceahern.com> wrote in message news:<mailman.1034738840.5064.python-list at python.org>...
> [Chris Fonnesbeck]
> > I am using python to code an optimization function that requires
> > numbers to be compared to one another, as is common in many
> > algorithms. However, the comparison operators (<,>,<=,>=,==) seem not
> > to be working properly. Regard the following:
> >
> > >>> print fb,fc
> >
> > 0.132945911028 0.132945911028
> >
> > >>> print fb>fc
> >
> > 1
> >
> >
> > These numbers look the same to me; what do I have to do to be able to
> > test numbers accurately in python?
>
> Looks can be deceiving. <wink>
>
> I wonder whether this is related to the floating point binary thing?
>
> >>> fb = 0.132945911028
> >>> fc = 0.132945911028
> >>> fb == fc
> 1
> >>> fb > fc
> 0
>
> So far, so good.
>
> However, consider this:
>
> >>> fd =
> 0.132945911027999999999999999999999999999999999999999999999999999999
> >>> fd
> 0.13294591102799999
>
> Hmm, that's the __repr__, I believe.
>
> What about the __str__:
>
> >>> print fb, fc, fd
> 0.132945911028 0.132945911028 0.132945911028
>
> Yeah, they "look" the same...
>
> >>> fd == fb
> 1
>
> Does that help? What kind of precision do you need in your numbers?
>
> // mark
>
> -
More information about the Python-list
mailing list