Python, mysql, floating point values question

Terry Hancock hancock at anansispaceworks.com
Fri Jul 1 22:23:13 EDT 2005


On Friday 01 July 2005 05:40 pm, Christopher Kang wrote:
> Anyway, I have a problem where I am pulling floating point values out
> of mysql and into python using the MYSQLdb module.
> 
> However, the values seem to be altered a little when I store them in python.

I'm not even going to start to explain why, but this is a given with
floating point values. They *always* have a degree of imprecision.
You're just tickling this problem by changing representations from
Python to SQL and back.

Long, long ago when all I knew how to program in was Basic and
Fortran, I learned the fundamental rule of comparing floats --- you
must always allow a tolerance, e.g.:

epsilon = 0.0001
if abs(a-b) > epsilon:
    print "a ~= b"
else:
    print "a != b"

There is no "equals" with floating point numbers. Just remember that,
and you'll go far. ;-)

As for how to do this in SQL? I'm pretty sure that you can do
ranges in SQL, but I'd have to look up the syntax for inequality
statements.  The python equivalent would be to write it out as:

if  a > b-epsilon and a < b+epsilon:
    print "a~=b"

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list