有没有办法在Matlab中将$ 0 $和$ 1 $之间的十进制数转换为基数为4的整数?例如。如果我把2/5我想得到0.12121212 ...(我估计有一些近似值)
函数dec2base
仅适用于整数。
答案 0 :(得分:4)
本文中列出的是一种矢量化方法,它通过所有可能的数字组合来为最终输出选择最佳输出作为字符串。请注意,由于其创建所有可能组合的本质,它将是内存密集型并且比递归方法慢,但我想它可以仅用于娱乐或教育目的!
这是函数实现 -
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