On Tue, Apr 20, 2010 at 11:58 AM, Lowell Tackett
<lowelltack...@yahoo.com> wrote:
> I'm running headlong into the dilemma of binary math representation, with 
> game-ending consequences, e.g.:
>
>>>> 0.15
> 0.14999999999999999
>
> Obviously, any attempts to manipulate this value, under the misguided 
> assumption that it is truly "0.15" are ill-advised, with inevitable bad 
> results.
>

Yes, floats are slightly inaccurate.
No, this usually doesn't cause problems.

You can use the decimal module if you want.
But I think your problem is that your math is wrong.
You are assuming that your float values are precise and they are not.
You must check ranges when dealing with float values, not for specific values.
I.E. you should never depend on a value being 1 in a float calculation,
instead your equations need to be robust enough to deal with values
very close to 1 as well.
If your equations cannot handle this, then coerce the value to 1.
if .9999999 < i < 1.00001:
    i = 1

And before you say "but that is just a hack", no, that is the nature
of floating-point values.  No one ever claimed that they were precise
or that you should depend on their values being precise.

If you really care so much, use the decimal module.
But you really just need to adapt your formulas from the ideal to the
reality, in which the values are not necessarily complete.

May I suggest another approach though?
Why even process these values as floats?

Consider this:
>>> a = 18.15
>>> a
18.149999999999999
>>> a = '18.15'
>>> degree, min = map(int, a.split('.'))
>>> degree
18
>>> min
15

Supposing you get your input as a string.
Basically the second you let your value end up stored as a float,
there's no turning back.  You need to get ahold of this value before
it becomes a float and deal with it in a different way.  The most
straightforward is to deal with the parts individually as integers.

Eventually you will develop a distrust for floats and you will
intrinsically know where and when you should / shouldn't use them ;)

Hope that helps,
-Luke
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to