decimal to binary conversion of recurring decimal numbers

4 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 15 Jan 2016
Edited: Stephen23 on 15 Jan 2016
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:

More Answers (1)

Nef Tur
Nef Tur on 24 Nov 2020
Hı, I could not do this question. Can you help me

Categories

Find more on Programming 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!