0
$\begingroup$

I have made a function convert fractional part of a decimal number to binary, the code is given below:

function [ ret ] = de2bi_( in, itt )
ret='';
for i=1:itt
    in = mod(in,1);
    in = in*2;
    ret = strcat(ret, (num2str(floor(in))));
end
return;
end

here itt is the number of digits required in binary. But when I pass the value of pi it returns the following value

0010010000111111011010101000100010000101101000110000000000000000000000000000000000000000000000000000

which is obviously wrong. Same is the case for any other recurring rational or irrational decimal number. How to solve this issue.

$\endgroup$
1
$\begingroup$

there is nothing wrong, in matlab as in any programming language $\pi$ is represented by a double precision floating number, i.e. a rational number of the form $N 2^{-k}$ where $N,k$ are integers.

$\endgroup$
  • $\begingroup$ Is there any way to overcome this issue? $\endgroup$ – Ameer Hamza Jan 15 '16 at 9:02
  • $\begingroup$ using big integers or symbolic calculus (symbolic toolbox or mapple or mathematica or a special library). what do you want to do ? $\endgroup$ – reuns Jan 15 '16 at 9:05
  • $\begingroup$ I got it working using symbolic toolbox. Thanks. $\endgroup$ – Ameer Hamza Jan 15 '16 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.