Infinite loop when decimals are added
1 次查看(过去 30 天)
显示 更早的评论
I am making a simple program to calculate the number of times a decimal number has to be multiplied (by positive integers) so that the decimal part (mod1) will = 0.
Example of the code:
%Decimal
ro=0.5854;
n=1;
while mod(ro*n,1)~=0
n=n+1;
end
n
In this case the answer is 5000.
I want to be able to change the last digit of the decimal point. But I am having a problem when I make a small change in the program. I get an infinite loop. The changed program is shown below:
%Decimal
ro=0.585+0.0004;
n=1;
while mod(ro*n,1)~=0
n=n+1;
end
n
I can't understand why I get an infinite loop with this small change - the value of ro changed acordingly but I get an infinite "while" loop. Please explain.
0 个评论
采纳的回答
Stephen23
2022-7-30
移动:Walter Roberson
2023-1-22
"Please explain"
Different accumulated floating point error combined with an algorithm that does not take into account the behavior of binary floating point numbers. Also note that the values are not the same:
fprintf('%.30f\n', 0.5854, 0.585+0.0004)
Read more about binary floating point numbers:
This is worth reading as well:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 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!