Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Pedro Gilbert   on Sep 05 In Java Category.

  
Question Answered By: Benjamin Simpson   on Sep 05

The opposite of power function is a logarithm. The logarithm of
a number is the power you raise the base to get that number.
This is difficult to type without using subscripts, but I'll try. If you
raise 2 to the power of 10, you get 1024.
log(base2) 1024 = 10

Now, you don't get a log(base2) function in the API, but you don't
need it as you can convert a log of any base using this formula:

log(base a) x = (ln x) / (ln a)

where ln is a natural logarithm (base e). So in your case, that
gives us:

log(base 2) 1024 = (ln 1024) / (ln 2)
= 6.931471806 / 0.69314718
= 10

which was what you wanted. In Java:

double getPower(double base, double  d) {
return (Math.log(d) / Math.log(base));
}

so if you call it with

getPower(2, 1024);

it should return 10.

Share: