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.

2 Kommentare

Adam
Adam am 10 Apr. 2019
It is not possible to store every floating point number precisely so there are errors that accumulate when they are summed (or other operations) which is why you will not get exactly 100 as your answer.
Read up about floating point arithmetic to understand further.
MAHMOUD ALZIOUD
MAHMOUD ALZIOUD am 10 Apr. 2019
Thank you for your help, I will try it now

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Star Strider
Star Strider am 10 Apr. 2019

0 Stimmen

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.

4 Kommentare

MAHMOUD ALZIOUD
MAHMOUD ALZIOUD am 10 Apr. 2019
Thans, I tried it but still having a sum of 100.01, is there any command to tell MATLAB that if the summation is not 100 please add or subtract 0.01 from any one of the 10 cases?
As always, my pleasure.
I would just use the round (link) function on the result.
Note that if you round the interim calculations to the nearest 0.01, the rounded result is not exactly the value you want.
Example —
x = rand(5,1)*100
r = round(x,2)
producing:
x =
16.716840991465599
10.621634492866383
37.240974005553696
19.811840254297465
48.968763801602385
r =
16.719999999999999
10.619999999999999
37.240000000000002
19.809999999999999
48.969999999999999
MAHMOUD ALZIOUD
MAHMOUD ALZIOUD am 10 Apr. 2019
Yes I got it now, Thank you for your help
Star Strider
Star Strider am 10 Apr. 2019
As always, my pleasure.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by