Skip to main content

How do you write a negative exponent method in java?

1 reply [Last post]
slynnie90
Offline
Joined: 2012-03-20
Points: 0

I have an assignment requiring me to create a negative exponent method in java, but I have no idea how to do so. I am very very very new to java, and do not understand how to get started...please help!

These are the instructions I was given:

How do you write a negative exponent method in java? These are the instructions I was given: In order to complete the calculation, you'll need to write a method to compute the value a^b when b is a negative integer:

public static double pow(double a, int b)

Recall that ab is a / a-b. For example, 1.5-3 = 1 / 1.53. Likewise, recall that 1.53 is 1.5 times itself a total of three times: 1.5 x 1.5 x 1.5. You can also view this as 1.5-3 = 1 / 1.5 / 1.5 / 1.5. I cannot use math.pow. I was told that I have to use a for loop to get the function working properly, but I do not know where to begin. Here is what I have, but it is using math.pow, which it cannot use:

public static void main(String[] args) {

double result = 1;
for( int k=0;k<Math.abs(b);k++ ) {
...result = result/b;
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
gsjava
Offline
Joined: 2012-03-21
Points: 0

public static double pow(double base, double exponent) {
double result = 1;

if (exponent == 0) {
return result;
}
if (exponent < 0) {
return 1 / pow(base, exponent * -1);
}
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
return result;
}