user7283235
user7283235

Reputation: 101

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

Upvotes: 2

Views: 778

Answers (2)

Rohit
Rohit

Reputation: 2017

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.

Upvotes: 2

Maurits Evers
Maurits Evers

Reputation: 50678

I'm not entirely sure what you're asking but log2 gives you the logarithm base 2 in R. For example

log2(2);
#[1] 1

log2(2^10)
#[1] 10

2^(log2(10))
#[1] 10

See ?log for details.

Upvotes: 0

Related Questions