Rounding error in simple addition

dhumphries
2024-04-27
2024-05-25
  • dhumphries - 2024-04-27

    I have discovered a rounding error, either in Codesys or in my understanding of numbers. The attached ladder shows that when the up button is pressed the number increases by 0.1, when the down button is pressed number decreases by 0.1, after several button presses the number isn't equally divisible by 0.1.

    Have I discovered a bug or am I doing something wrong?

     

    Last edit: dhumphries 2024-04-27
  • dhumphries - 2024-05-24

    Bump

     
  • ndzied2 - 2024-05-24

    This is a consequence of how computers store floating point numbers. 0.1 cannot be exactly represented in a computer. This is not a CoDeSys thing. Here is a link to a converter to show you the exact value that is represented when you use a REAL data type (which is a 32 bit float).
    https://baseconvert.com/ieee-754-floating-point

    If you really need to keep track of 0.1 increments. use INT OR DINT and then add 1 each time and assume that there is one decimal place.

     
  • ndzied2 - 2024-05-24

    Ignore, was duplicate post. Can't find a way to delete it.

     

    Last edit: ndzied2 2024-05-24
  • dhumphries - 2024-05-25

    Thanks for the response, as I've thought about this problem over the last month I began to suspect this was a problem with not being able to exactly represent .1 as a 32 bit binary number. I think I've found a work around by making the number an integer, then dividing it by 10 and storing that value as a floating point number. There is still an issue with the value not being exact somewhere in the 8th or 9th decimal place, but because I'm incrementing an integer value then dividing it, the error doesn't compound.

     

Log in to post a comment.