Using the floor function to separate numbers

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Roger Stafford
Roger Stafford il 21 Apr 2016
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 Commento
dillon-harris
dillon-harris il 21 Apr 2016
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.

Accedi per commentare.

Più risposte (1)

Star Strider
Star Strider il 21 Apr 2016
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 Commento
dillon-harris
dillon-harris il 21 Apr 2016
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.

Accedi per commentare.

Categorie

Scopri di più su Operators and Elementary Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by