在 Matlab 中将非整数的十进制数转换为基数 4?

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

有没有办法在 Matlab 中将 $0$ 和 $1$ 之间的非整数十进制数转换为基数 4?例如。如果我放 2/5 我想得到 0.12121212...(我猜有一些近似值)

函数dec2base只适用于整数。

在此 post 中列出的是一种矢量化方法,它通过所有可能的数字组合来 select 最终输出为字符串的最佳组合。请注意,由于其创建所有可能组合的本质,它会占用大量内存并且比递归方法慢,但我想它可以仅用于娱乐或教育目的!

下面是函数实现-

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;

样本运行 -

>> 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