number comparison problem

Mark McEahern marklists at mceahern.com
Tue Oct 15 23:26:08 EDT 2002


[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