Using the floor function to separate numbers

조회 수: 2 (최근 30일)
dillon-harris
dillon-harris 2016년 4월 21일
댓글: dillon-harris 2016년 4월 21일
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

채택된 답변

Roger Stafford
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
dillon-harris
dillon-harris 2016년 4월 21일
Thank you for the timely response. I did not even know of the error associated with binary floating point representation.Makes sense now why it was true for ~=0. I can now factor this into future calculations.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Star Strider
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.
  댓글 수: 1
dillon-harris
dillon-harris 2016년 4월 21일
Thank you for the timely response. I did change the format to long E, and it provided a good visual with what was happening with the floating-point approximation error. Also moving the 'a' increment inside the if statement was great as it got rid of the zeroes in the matrix, when previously i would write an additional line of code to do so.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by