Search code examples
rmatlablogarithm

log2 in R: How to calculate the exponent and mantissa


Does anyone know how to carry out the same MATLAB function [F,E] = log2(X) in R?

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

See https://www.mathworks.com/help/matlab/ref/log2.html

For example in MATLAB,

[F,E] = log2(15)

F =

0.9375

E =

 4

Thus,

F*2^E = 15


Solution

  • You'll need to calculate them manually. I don't think there's a builtin to extract them. Try this:

    x<-15
    E <- ifelse(x == 0, 0, floor(log2(abs(x)))+1 )
    F<-x/2^E
    

    Edit: Made the change for the case of x==0.