Home > Software engineering >  Iterative Newton's Method to recursive (Java)
Iterative Newton's Method to recursive (Java)

Time:12-16

I need to use Newton's method using recursion. I have this piece of code using iterative Newton's method, but I'm very new to programming so I can't wrap my head around how to turn it into recursion. I would really appreciate some visual demonstration.

public static double f(double x){ 
    return x*x*x-3.5*x*x 0.5*x   5;
}
public static double prf(double x) { 
    return 3 * x * x - 7 * x   0.5;
}
// ВЫЧИСЛЕНИЕ КОРНЯ МЕТОДОМ НЬЮТОНА
public static double x_newton(double a, double e) {
    double x = a; 
    double razn;
    do {
        double xn = x - f(x) / prf(x); 
        razn = Math.abs(xn - x); 
        x = xn; 
    } while (razn > e); 

    return x - f(x)/prf(x); 
}

CodePudding user response:

Usually we want to go other way around, that is, eliminate the recursion. In case of a tail recursion:

func(arguments) {
    if (condition) {
        return something(arguments)
    }
    arguments = modify_arguments(arguments)
    return func(arguments)
}

there is a mechanical rewrite:

func(arguments) {
    while (!condition) {
        arguments = modify_arguments(arguments)
    }
    return something(arguments)
}

Now you only need to apply it backwards.


That said, while (razn > e) is not a robust way to terminate the loop. In case the derivative is very large, it may terminate too early, far away from the root.

Also, use English for identifiers. razn looks equally ugly for both Russian and English reader. delta_x is way better. Ditto for pr.

  • Related