Using the floor function to separate numbers
2 次查看(过去 30 天)
显示 更早的评论
I am working on an assignment where I have to list all the numbers from 1-200 whose individual sum is odd (e.g 12 = 1 + 2 = 3 and therefore odd, and shall therefore be placed into an array. I have written the code where I am only testing the numbers from 10:18 just to make sure the concept works on a small scale. The problem I am having is removing the number 11 from my output array. With the code I have written, it does not make sense to me why the 11 still remains. Please can someone assist.
a = 0;
for k = 10:18;
a = a + 1;
initial = k / 10;
initial2 = floor(initial);
secondary = (initial - initial2)*10;
outcome = secondary + initial2;
if mod(outcome,2) ~=0
arrayinitialodd(a) = [k]
end
end
///////////////////////////////
output:
arrayinitialodd =
10 11 12 0 14 0 16 0 18
///////////////////////////////////////
Proof of operation I get in the command window with respect to the number 11:
a = 2
initial = 1.1000
initial2 = 1
secondary = 1.0000
outcome = 2.0000
value = 11
arrayinitialodd =
10 11
0 个评论
采纳的回答
Roger Stafford
2016-4-21
Your mistake occurs at the line:
secondary = (initial - initial2)*10;
You should have written
Secondary = k - initial2*10;
The quantity initial = k/10 is a number your computer, which is using binary floating point representation, cannot represent precisely. It must necessary have a very tiny error. When you multiply back again by 10, the result is a tiny bit off from an exact integer, so the test
mod(outcome,2) ~=0
comes out true even though 'outcome' in this case is very close to 2. If you look at an exact value for it, you will discover that.
更多回答(1 个)
Star Strider
2016-4-21
You’re experiencing floating-point approximation error. You can see that if you change to format long E and remove the semicolon from your ‘outcome’ assignment.
Solution: use mod or rem for secondary instead:
secondary = rem(k,10);
Also, put the ‘a’ increment inside the if block.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!