MATLAB: Decimal to binary conversion of recurring decimal numbers

base conversionbinarydecimal

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.

Best Answer

MATLAB's default numeric type is the IEEE 754 double, and you have reached its precision limit. Every double floating-point number has a 52 bit significand (giving about 15-17 decimal digit precision). It is not possible to squeeze more digits of information out of this numeric than it actually contains.
If you want to calculate to higher precisions than double supports then you need to convert your function to work with vpa:
or check out some of the FEX submissions that support higher numbers of digits: