floating points and precision

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MikePoules
    New Member
    • Oct 2011
    • 2

    floating points and precision

    I am writing a test harness for a piece of code that will run on a DSP. It uses floats and i need to simulate their manipulation. The problem is that as i decrement a float (say by 0.005) errors accumulate so when i need to do a compare the low end decimals are inacurate. ie if i need to comapre a number to 0.05 it may read as 0.049999999 and so will be false.
    I have looked arounding, casting and the use of sprintf like statements but can't see around the problem. Any help would be greatfully recieved.
    Oh and i am using visual C++ dev environment
    Thanks in advance
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    You may be able to get round this by declaring a const tol (tolerance)valu e like
    Code:
    float const tol = 0.00005
    which modifies the value of other variables much as ceil() and floor() functions perform by rounding up or down to the nearest integer value(while retaining their float types.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      There is no real way round this problem, float and double types are approximations and are always subject to errors in the lower bits. You should never use the comparisons == or != with these types because in general they will only every give 1 result either true or false.

      Code:
      // Exmaple
      float f;
      int i;
      
      // some coding setting the value of f and i and manipulating them
      
      if (i == 5) // Could return true or false depends if i is 5 or not
      {
      }
      
      if (f == 5.0) // Always returns false f will never be exactly 5.0
      {
      }
      There are some mitigations you can do for example using a tolerance as whodgson suggests

      Code:
      if (f >= 4.9 && f <= 5.1) // Returns true or false depending of f being close to 5.0
      {
      }
      and you can increase the accuracy of calculations where comparitivly smaller values are being added (or subtracted) repeatedly from large ones with, for example the Kahan summation algorithm.

      But ultimately you can never get away from the possibility that the float is going to have a slightly different value to what you are expecting.

      try reading this, "What Every Computer Scientist Should Know About Floating-Point Arithmetic"

      Comment

      • MikePoules
        New Member
        • Oct 2011
        • 2

        #4
        I sort of got to that conclusion myself. So wghat i do now is subtract the numbers and look at the size of the error making assumptions based on that size. Not perfect i know but it for my situation it seems to work.
        Thanks for the input

        MIKE

        Comment

        Working...