我在类中声明了专用的Complex变量“ root”。 我在void方法“ iterate”中将root的值设置为复数
我希望打印'root'的新值(第60行),但是当我尝试时,它将打印为null。因此,我认为这不是正确的“根”。
我的代码:
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);
}}
答案 0 :(得分:0)
您需要在git pull https://github.com/someuser/someproject.git
类中为root
创建一个吸气剂,因为它是一个私有字段。
Newton
然后,您可以使用吸气剂代替尝试访问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();
}
public Complex getRoot(){
return this.root;
}
}
(即,使用n.root
代替newtonObj.getRoot()
)
newtonObj.root