Bad Math

Brian van den Broek bvande at po-box.mcgill.ca
Sat Jul 2 15:22:17 EDT 2005


Patrick Rutkowski said unto the world upon 02/07/2005 09:25:
> On 7/2/05, Brian van den Broek <bvande at po-box.mcgill.ca> wrote:
> 
>>Patrick Rutkowski said unto the world upon 02/07/2005 00:12:
>>
>>>That's... annoying, to say the least. And my number 4/5 was a rational
>>>number too; I can understand how when doing 1/3 things can get funky.
>>>Really though... 4/5 = 0.8 right on the nose, whats up?
>>>
>>>I read that http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate
>>>I'd like to find out more, is there anyway for this issue to be
>>>circumvented? That "is within a reasonable limit check" seams like way
>>>too much just to get a proper result from something simple like 4/5.
>>>
>>>
>>
>>Hi Patrick,
>>
>>my quick piece of code became something I thought might someday be
>>useful. So, I expanded it with tests, and sanity checks, etc. It
>>doesnt' yet have the full functionality I'd like (see docstrings), but
>>I won't get to fixing it anytime real soon.
>>
>>So, in case you are interested, it is attached. It allows you to
>>compute the value of a rational[*] as expressed in any base, 1 < base
>>< 37, to arbitrary precision.

<snip my probably very clumsy code>


> I just got up and read your mail. However, I'm going away for the day
> so I didn't have time to look over your code. Thanks for the advice
> and explanations, they really helped. I understand the problem now...
> /me waves fist a base 2 fractions. If your code can fix it, then
> that's pretty great! What was that "import decimal" idea you proposed?
> Does it contain some functions that can sanely work with floating
> points? I'm not a new programmer, but my main arena is the simple side
> of Java, so I'm not really too far along yet.
> 
> Hoping Python will be fun,
> Patrick Rutkowski
> 
> P.S. I responded to the list this time.


Hi all,

:-(

Patrick had originally posted with the "why is Python getting the math 
wrong?" floating point issue. I'd responded to him with the FAQ link. 
He wrote back privately (top of quoting above). I replied privately 
and explained that the "better" behaviour of 4/5.0 as compared to 
1/3.0 is a product of base 10 representation. To substantiate this, I 
coded up something (incomplete) to represent rationals in arbitrary 
bases, for base 1< base < 37, and sent it privately.

Patrick then replied to the message with that code to the list :-( I'd 
not intended it to be posted publicly, not out of any code hoarding 
impulse, but from thinking it isn't good enough to put forth to the 
world. (I'm only a hobbyist.) But, since the decision to put it out 
there was taken for me, if anyone read the code, I'd appreciate 
comments. (The code is in the msg to which this is a reply -- it is 
long enough I didn't want to post it twice.)

Thanks, and best to all,

Brian vdB




More information about the Python-list mailing list