Acron
Acron

Reputation: 1398

Why is my Variable set to 0?

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?

Upvotes: 0

Views: 351

Answers (6)

NawaMan
NawaMan

Reputation: 25687

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.

Upvotes: 5

DigitalRoss
DigitalRoss

Reputation: 146093

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

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

Upvotes: 0

James Black
James Black

Reputation: 41858

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

Upvotes: 0

Taylor Leese
Taylor Leese

Reputation: 52330

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) { ... }

Upvotes: 1

Carl Smotricz
Carl Smotricz

Reputation: 67760

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!

Upvotes: 1

Jorge Israel Pe&#241;a
Jorge Israel Pe&#241;a

Reputation: 38606

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.

Upvotes: 0

Related Questions