views:

104

answers:

6
import java.lang.Math;
public class NewtonIteration {

    public static void main(String[] args) {
     System.out.print(rootNofX(2,9));
    }

    // computes x^n
    public static double power(double x, int n) {
     if (n==0) {
      return 1;
     }  
     double Ergebnis = 1;
     for (int i=0; i<=Math.abs(n)-1; i++) {
      Ergebnis *= x;
     }
     if (n<0) {
      Ergebnis = 1/Ergebnis;
     }

     return Ergebnis;
    }

    // computes x^(1/n)
    public static double rootNofX(int n, double x) {
     return power(x, 1/n);
    }
}

Whenever power(x,1/n) is called, n is reset to 0. But isn't n a parameter given to rootNofX with the value 2?

A: 

It's because you're using integers, so 1 / 2 = 0.5 which as an integer is 0. Change the prototypes to rootNofx(double n, double x) and power(double x, double n).

Also, since rootNofx uses power, in my opinion, it would be better to have the parameters ordered the same way, to avoid confusion.

Jorge Israel Peña
2/1 is 0.5? This must be the new math I'm having so much trouble with! :)
Carl Smotricz
LOL! Sorry about that, I meant 1 / 2 :)
Jorge Israel Peña
+1  A: 

1/n is going to be a fraction, usually, but in the declaration of power you declare n to be integer. That's going to knock off the decimal places every time!

Carl Smotricz
+1  A: 

It's because power is defined with "n" as an int so 1/n will always be less than 1 which will be zero when stored as an int. Update "int n" to "double n". Example below:

public static double power(double x, double n) { ... }
Taylor Leese
+5  A: 

Try:

// computes x^(1/n)
    public static double rootNofX(int n, double x) {
        return power(x, 1.0/n);
    }

Because 1 is an int and n is an int so 1/n is an integer division which return 0 when n is not 1 and throw error when n is 0.

1.0 is a double so it make 1.0/n a double division that you want.

NawaMan
You also have to change the parameter `n` of the method `power` to `double`, else it still won't work.
hjhill
@hjhill: You do not need to. Try it. Cheer! :-D
NawaMan
A: 

The problem is that you are passing 1/2 from rootNofX into an int, so it becomes zero.

James Black
A: 

There is a big difference between 1/n and 1.0/n

Consider what declaring n to be an int really means...

DigitalRoss