Loop Question with divison
1 view (last 30 days)
Show older comments
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
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?
Accepted Answer
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
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.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!