Search code examples
matlabradix

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


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.


Solution

  • 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