Thread: Help Please
View Single Post
  #4 (permalink)  
Old 04-03-2008, 11:45 PM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Code:
public class NRTest { public static void main(String[] args) { NewtonRaphson f = new NewtonRaphson(); double x = 2; double root = f.solve(x); //System.out.println("root = " + root); } } class NewtonRaphson { // Our approximation of zero final double TOLERANCE = .000000005; // Maximum number of Newton's method iterations final int MAX_COUNT = 200; // f(x) = cos(x) private double f(double x) { return Math.sin(x); } // f'(x) = sin(x) private double fprime(double x) { return Math.cos(x); } public double solve(double x0) { System.out.printf(" %-8s%-13s%-12s%-16s%-15s%s%n", "n", "x_n", "f(x_n)", "f'(x_n)", "x_n+1", "dx"); double x = x0; int n = 0; do { x = x0 - f(x)/fprime(x); double dx = x - x0; System.out.printf("%2d %10f %10f %10f %10f %10f%n", n, x0, f(x), fprime(x), x, dx); x0 = x; if(Math.abs(dx) < TOLERANCE) break; } while(++n < MAX_COUNT); if( Math.abs(f(x)) <= TOLERANCE) { System.out.println("Zero found at x="+x); } else { System.out.println("Failed to find a zero"); } return x; } }
Reply With Quote