decimal to binary conversion of recurring decimal numbers in matlab

583 Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

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.