Reputation: 3
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!!!
Upvotes: 0
Views: 1026
Reputation: 112689
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
Upvotes: 2
Reputation: 221574
Try this approach using strings -
n = 0.320446597556797 %// Input decimal number
t1 = num2str(n,'%1.15f')
t2 = strfind(t1,'.')
a = str2num(reshape(t1(t2+1:end),5,[])') %// output as a single matrix
Thanks to @Luis for the reshape idea! Hope you won't mind Luis!
Upvotes: 2
Reputation: 8603
It is probably a rounding error but if you really want those specific values, simply cast to a string and then rip the string apart. Something simple like below
a = 0.320446597556797;
format longg
aStr = num2str(a,'%1.15f');
decimals = regexp(aStr,'\.','Split');
decimals = decimals{2};
a1 = str2double(decimals(1:5));
a2 = str2double(decimals(6:10));
a3 = str2double(decimals(11:15));
Upvotes: 0