Search code examples
matlabmatlab-deployment

Extracting digits after decimal MATLAB


I am representing a chaotic number with 15 digits after decimal i.e format long in matlab and i want to extract 3 numbers each containing 5 digits from the chaotic number. i.e if chaotic no. is 0.d1d2...d15 then i want (d1..d5),(d6..d10) & (d11..d15). it is always rounding off.I have written the following code.

num=x(n);
a1=floor(num*10^5);
disp('a1');
disp(a1);
a2=floor(num*10^10-a1*10^5);
disp(a2);
num=floor(num*10^15);
a3=mod(num,100000);
disp('a3');
disp(a3);

and the output is

0.320446597556797

a1
   32044
a2
   65975

a3
   56796

its showing a3 as 56796 but i want 56797.

please help!!!


Solution

  • The problem is, very likely, that each operation you do to extract a group of digits introduces a small error, which is reflected in the last digit.

    An alternative approach that avoids this:

    num = pi; %// for example
    str = num2str(num,'%0.15f'); %// string representation with 15 decimal digits
    str = str(find(str=='.')+1:end); %// keep only digits after decimal point
    a = base2dec(reshape(str,5,[]).',10); %'// convert string parts into numbers