CPE 315
Professor Stearns
Rules for Floating Point Numbers


Floating point numbers are quite useful and necessary for scientific calculations. But, many programmers use them improperly.
Follow these rules to avoid problems.
    Don't use floating point numbers if your answers must be exact.
    for example, if you are calculating dollar amounts, use fixed point numbers to get perfect answers.

  1. Never compare floating point numbers for equality
    Expressions such as if (num == 1.2) (probably) won't work.
    If you have no choice, use an expression such as:
        if (num > 1.2-epsilon && num < 1.2+epsilon)
    where epsilon is some small number.

  2. Never count with floating point numbers
    If you need to count with real numbers (e.g. 0.1, 0.2, 0.3, ...) use fixed point numbers.

  3. Floating point arithmetic isn't associative
    a + b + c != c + b + a


Last updated on 10/11/04