Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds


  Asked By: Pedro    Date: Sep 05    Category: Java    Views: 1944

I'm guessing that this is pretty simple but I'm not finding it and since I'm not
really a math kinda guy, I don't really know where to look. What's the opposite
of Math.pow(double a, double b)? In other words, I want to find out what b was
in order to raise a to the value returned my pow(). For example, let's say I
have 1024 and I want to know what exponent was used to raise 2 to 1024. I know
it's 10 but how do I do that programmatically?



2 Answers Found

Answer #1    Answered By: Taylor Evans     Answered On: Sep 05

It's been a while since I had to do anything like this, but I think that this
will work:

public static double  calcExponent(double b, double y)
return (Math.log(y) / Math.log(b));

Answer #2    Answered By: Benjamin Simpson     Answered 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.

Didn't find what you were looking for? Find more on Math.pow() Or get search suggestion and latest updates.