Convert a decimal number that is not integer to base 4 in Matlab?

╄→гoц情女王★ 提交于 2019-12-06 11:59:59

Listed in this post is a vectorized approach that works through all possible combinations of digits to select the best one for the final output as a string. Please note that because of its very nature of creating all possible combinations, it would be memory intensive and slower than a recursive approach, but I guess it could be used just for fun or educational purposes!

Here's the function implementation -

function s = dec2base_float(d,b,nde)
%DEC2BASE_FLOAT Convert floating point numbers to base B string.
%   DEC2BASE_FLOAT(D,B) returns the representation of D as a string in
%   base B.  D must be a floating point array between 0 and 1.
%
%   DEC2BASE_FLOAT(D,B,N) produces a representation with at least N decimal digits.
%
%   Examples
%       dec2base_float(2/5,4,4) returns '0.1212'
%       dec2base_float(2/5,3,6) returns '0.101211'

%// Get "base power-ed scaled" digits
scale = b.^(-1:-1:-nde);

%// Calculate all possible combinations
P = dec2base(0:b^nde-1,b,nde)-'0';

%// Get the best possible combination ID. Index into P with it and thus get
%// based converted number with it
[~,idx] = min(abs(P*scale(:) - d));
s = ['0.',num2str(P(idx,:),'%0.f')];

return;

Sample runs -

>> dec2base_float(2/5,4,4)
ans =
0.1212
>> dec2base_float(2/5,4,6)
ans =
0.121212
>> dec2base_float(2/5,3,6)
ans =
0.101211
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!