I declared the private Complex variable 'root' in my class. I set the value of root to a Complex number inside the void method 'iterate'
I wish to print the new value of 'root' (line 60) but when I try, it prints as null. So I don't think it is calling the correct 'root'.
My code:
class Newton {
public static final int MAXITER = 20;
public static final double TOL = 1.0e-10;
private Polynomial f; //Polynomial
private Polynomial fp; //Derivative of the polynomial
private Complex root;
private int numIterations;
private int err;
//Basic constructor. Calculate and set fp in this method.
public Newton(Polynomial p) {
this.f = p;
this.fp = p.derivative();
}
// Newton-Rapshon method
public void iterate(Complex z0) {
Complex[] z = new Complex[MAXITER];
z[0] = z0;
for(int i = 0 ; i<MAXITER ; i++){
if(fp.evaluate(z[i]).abs() <= TOL){
this.err = -1;
return;
}
z[i+1] = z[i].add((f.evaluate(z[i])).divide(fp.evaluate(z[i])));
if(f.evaluate(z[i]).abs() != TOL){
this.err = -2;
return;
} if (f.evaluate(z[i]).abs() <= TOL){
this.err = 0;
this.root = z[i];
this.numIterations = i;
return;
}
}}
// Tester function.
public static void main(String[] args) {
// Basic tester: find a root of f(z) = z^3-1 from the starting point
// z_0 = 1+i.
Complex[] coeff = new Complex[] { new Complex(-1.0,0.0), new Complex(),
new Complex(), new Complex(1.0,0.0) };
Polynomial p = new Polynomial(coeff);
Newton n = new Newton(p);
Complex z0 = new Complex(1.0,1.0);
n.iterate(z0);
System.out.println(n.root);
}}