[Tutor] [Long!] Varying degrees of precision

dman dsh8290@rit.edu
Tue, 31 Jul 2001 18:11:33 -0400


On Tue, Jul 31, 2001 at 04:53:14PM -0700, kromag@nsacom.net wrote:
| Hi all!
| 
| Sorry I've been a stranger lately, but I have been decending into C.
| 
| I have noticed that there are some weirdnesses occouring when converting 
| integers to floats in python. I wrote the following module as the beginnings 
| of a "hot rod math" project. The first function, suck() gives the proper cfm 
| flow for a carburetor on an engine of a given size at a given rpm.
 
[...]
 
| >>> from rodney import suck
| >>> suck(2000,6000,'cc')
| 155.61115518398728
| >>> suck(2000.00,6000.00,'cc')
| 180.10550368517048
| >>> 
| ------------end rodney output------------
| 
| note the differences in the results!
| 
| I figured this out when I wrote the following lame C program:

[...]

| which returns 180.105499
|  
| Is this a case of weak typing biting me on the backside, or is there a 
| pythonic way to specify a float?


--- original answer, not really pertinent but might be interesting to some ---
Floats cannot represent all values.  They can only repesent values
that follow the form 1.n * 2**m  where n and m are integers and n is
displayed in binary.  Some numbers, for example .1 in decimal, can't
be represent exactly so they are approximated.  Anytime you perform
arithmatic using approximations the uncertainty of the result
increases (ie the amount of potential error from the correct answer).
If you want a really accurate (may be, but not necessarily will be
precise though) result use integers only.
----------------------------------------------------------------------

Anyways, I just noticed where your real problem lies

>>> suck(2000,6000,'cc')
         ^^^^ ^^^^

Those are integers.  Your function doesn't explicitly convert them to
floats so when you do division you get an integer back.  Think of
integer division like in 5th grade, but you simply ignore the
"remainder" part.

For example :

>>> 2 / 3
0
>>> 2.0 / 3.0
0.66666666666666663
>>>

If you convert the arguments to floats using the float() built-in
function before performing the division then it should work much
better :-).

HTH,
-D