Why does my while loop not work for this specific data-set?
이전 댓글 표시
I have written the following function, that effectively adjusts rounding errors. The code appears to get stuck in a while loop despite the condition of sum(roundedAssetAllocation) == 1. Could someone help to explain why?
function [a, n] = fixRounding(x, s)
u = 10.^-s;
n = length(x);
assetAllocation = x/sum(x);
roundedAssetAllocation = round(assetAllocation, s);
while sum(roundedAssetAllocation) ~= 1
diffFromUnrounded = assetAllocation - roundedAssetAllocation;
if sum(roundedAssetAllocation) < 1
[~, index] = max(diffFromUnrounded);
roundedAssetAllocation(index) = roundedAssetAllocation(index) + u;
elseif sum(roundedAssetAllocation) > 1
[~, index] = min(diffFromUnrounded);
roundedAssetAllocation(index) = roundedAssetAllocation(index) - u;
end
a = roundedAssetAllocation;
end
end
The following call should return: [.3485, .1198, .1356, .1761, .2200], but it instead gets stuck in a loop.
fixRounding([0.837746777686794, 0.287856637640281, 0.325810457772455, 0.423276428672838, 0.528787529659317], 4)
채택된 답변
추가 답변 (1개)
Jan
2017년 2월 20일
0 개 추천
You cannot assume that the sum of some double values is exactly 1.0 only by varying the inputs by adding or subtracting 10.^-s. See the frequently asked question: Answers: why-is-0.3-0.2-0.1-not-equal-to-zero . This is an effect of storing decimal values in the binary IEEE754 format: The most decimal numbers do not have an exact binary representation and the conversion can create some rounding "errors".
The solution is to work with tolerances, but this is more or less arbitrary.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!