MATLAB: How to fix the digits for the summation

digitsroundingsummation

Dear All, I have a code that finds the percentage of each case from the total population, I have 10 cases and the summation of their percentages must be 100% or 0 for example, but the problem is that I am still getting a summation of 100.01 or 99.99 or 99.98, what is the reason here and how can I fix it please, Notice: I rounded the results into 2 digits before I calculate the summation.

Best Answer

See the documentation section on Floating-Point Numbers (link). You are most likely seeing the result of floating-point approximation error. Also, rounding the numbers first loses precision, and likely results in the inaccuracies you get. The solution is not to round the intermediate values, only the results, and the only if necessary.
Related Question