Main Content

log2

Base 2 logarithm and floating-point number dissection

Description

example

Y = log2(X) computes the base 2 logarithm of the elements of X such that 2Y=X.

example

[F,E] = log2(X) returns arrays F and E such that X=F2E. The values in F are typically in the range 0.5 <= abs(F) < 1.

Examples

collapse all

X = [0 1 2 10 Inf NaN];
Y = log2(X)
Y = 1×6

      -Inf         0    1.0000    3.3219       Inf       NaN

Dissect several numbers into the exponent and mantissa. These operations all follow standard IEEE® arithmetic.

Create a vector X that contains several test values. Calculate the exponent and mantissa for each number.

X = [1 pi -3 eps realmax realmin];
format rat
[F,E] = log2(X)
F = 
       1/2          355/452         -3/4            1/2            1              1/2     

E = 
       1              2              2            -51           1024          -1021       

Collect the results in a table. Convert the numbers into character vectors for display purposes.

x = {'1','pi','-3','eps','realmax','realmin'}';
f = strtrim(cellstr(rats(F')));
T = table(x,f,E','VariableNames',{'Value','Mantissa','Exponent'})
T=6×3 table
       Value        Mantissa      Exponent
    ___________    ___________    ________

    {'1'      }    {'1/2'    }         1  
    {'pi'     }    {'355/452'}         2  
    {'-3'     }    {'-3/4'   }         2  
    {'eps'    }    {'1/2'    }       -51  
    {'realmax'}    {'1'      }      1024  
    {'realmin'}    {'1/2'    }     -1021  

The results indicate that, for the first row, 1=12(21). Similarly, for the fourth row, eps=12(2-51).

Input Arguments

collapse all

Input matrix, specified as a scalar, vector, matrix, multidimensional array, table, or timetable.

For floating-point number dissection [F,E] = log2(X), any zeros in X produce F = 0 and E = 0. Input values of Inf, -Inf, or NaN are returned unchanged in F with a corresponding exponent of E = 0.

Data Types: single | double | table | timetable
Complex Number Support: Yes

Output Arguments

collapse all

Base 2 logarithm values, returned as a scalar, vector, matrix, multidimensional array, table, or timetable of the same size as X.

Mantissa values, returned as a scalar, vector, matrix, multidimensional array, table, or timetable of the same size as X. The values in F and E satisfy X = F.*2.^E.

Exponent values, returned as a scalar, vector, matrix, multidimensional array, table, or timetable of the same size as X. The values in F and E satisfy X = F.*2.^E.

Tips

  • This function corresponds to the ANSI® C function frexp() and the IEEE® floating-point standard function logb(). Any zeros in X produce F = 0 and E = 0.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Version History

Introduced before R2006a

expand all

See Also

| |