[Tutor] when 1 is not equal to 1...??

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jul 16 23:00:38 CEST 2004



On Fri, 16 Jul 2004, Carla A. Ng wrote:

> I've put in an error catch in a program to alert me when the equations
> I'm trying to solve have an error.
>
> Basically, if the sum of contributions to something does not equal 1, it
> should print out an error message (I don't plan on keeping this in my
> code, since it's bulky and outputs a bunch of stuff to the screen, but I
> wanted to make sure everything was working correctly).  But I'm getting
> an error message when it *does* equal 1.


Hi Carla,

You may be running into floating point representation errors:

    http://www.python.org/doc/tut/node15.html
    http://www.lahey.com/float.htm

It's in the nature of floating-point that it's inexact.  Whenever we're
doing some kind of numerical method with floating point numbers, instead
of comparing floating point numbers for exact equality, we may need to
compare with some kind of "tolerance" in mind.

(Trivia: in fact, some programming languages just won't allow an the
equality-check between floating point numbers; Standard ML is one example
of a language that disallows comparing floats for equality.)


Anyway, I'd recommend using a small routine to check for equality within a
tolerable epsilon:

###
def closeEnough(a, b, tolerance=0.0001):
    """Returns true if 'a' and 'b' are close enough to each other."""
    return abs(a-b) < tolerance
###


Hope this helps!



More information about the Tutor mailing list