Loop Question with divison

1 view (last 30 days)
WhatIsMatlab-
WhatIsMatlab- on 20 Feb 2016
Commented: WhatIsMatlab- on 20 Feb 2016
I have the number 0.357. I want to multiply the number by 2 until it gets to a whole number. Once it gets to a whole number I want to subtract the whole number from 1 and then multiply by 2 until it becomes a whole number again. And I would like this to happen a specific number of times also.
  • This what I am trying to get my code to do. (Below)
0.357 *2 = 0.714
0.714 * 2 = 1.428
0.428 * 2 = 0.856
0.856 * 2 = 1.712
0.712 * 2 = 1.424
Thanks
  2 Comments
James Tursa
James Tursa on 20 Feb 2016
What have you done so far? Do you know how to program a for loop? Do you know how to program an infinite while loop?
WhatIsMatlab-
WhatIsMatlab- on 20 Feb 2016
Edited: WhatIsMatlab- on 20 Feb 2016
This is what I currently have. I am not sure I do. I want it to produce the values of m = [0 1 0 1 1]
m = [];
numbers = 0.357;
for i = 0:1:4
if numbers > 1
m = [m 1];
numbers = numbers - 1;
elseif numbers < 1
numbers= numbers*2;
m = [m 0];
end
end
display(m)

Sign in to comment.

Accepted Answer

Roger Stafford
Roger Stafford on 20 Feb 2016
Edited: Roger Stafford on 20 Feb 2016
For the precise number 0.357, which equals 357/(2^3*5^3), you can never arrive at an exact whole number by repeatedly multiplying by 2 since the prime factors 5^3 can never be cancelled out. However if you use matlab's double precision approximation for 0.357, you will actually arrive at a huge whole number at the end of 54 multiplications by 2.
Subtracting that whole number from 1 gives a negative number and multiplying a negative number by 2 will always result in another negative number, so you can never arrive at another whole number that way - whole numbers must be non-negative.
To carry out the first of the above steps, use a 'while' loop with a test for a whole number: floor(number)==number. (We know the results are always non-negative in this first step.)
  7 Comments
Roger Stafford
Roger Stafford on 20 Feb 2016
What I have shown you in the most recent comment is what you originally asked for and showed in your sample computations. Getting the string of 1's and 0's that you computed later is tantamount in this case to converting your original number to a binary fraction. It should be easy for you to modify the 'while' loop I gave you to produce that string. Just test that floor(n) when you obtain it before subtracting from n.
WhatIsMatlab-
WhatIsMatlab- on 20 Feb 2016
Ok!! I think I see what you are saying now. Let me give it a go. And see what happens. I apologize, I was just having a hard time understanding before.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!