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

好久不见. 提交于 2019-12-07 21:24:04

问题


Is there a way to convert a decimal number between $0$ and $1$ that is not integer to base 4 in Matlab? E.g. if I put 2/5 I want to get 0.12121212... (with some approximation I guess)

The function dec2base only works for integers.


回答1:


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


来源:https://stackoverflow.com/questions/37488951/convert-a-decimal-number-that-is-not-integer-to-base-4-in-matlab

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