1 16 17 package org.apache.commons.math.analysis; 18 19 import org.apache.commons.math.ConvergenceException; 20 import org.apache.commons.math.FunctionEvaluationException; 21 22 30 public class NewtonSolver extends UnivariateRealSolverImpl { 31 32 33 static final long serialVersionUID = 2606474895443431607L; 34 35 36 private UnivariateRealFunction derivative; 37 38 42 public NewtonSolver(DifferentiableUnivariateRealFunction f) { 43 super(f, 100, 1E-6); 44 derivative = f.derivative(); 45 } 46 47 58 public double solve(double min, double max) throws ConvergenceException, 59 FunctionEvaluationException { 60 return solve(min, max, UnivariateRealSolverUtils.midpoint(min, max)); 61 } 62 63 75 public double solve(double min, double max, double startValue) 76 throws ConvergenceException, FunctionEvaluationException { 77 78 clearResult(); 79 verifySequence(min, startValue, max); 80 81 double x0 = startValue; 82 double x1; 83 84 int i = 0; 85 while (i < maximalIterationCount) { 86 x1 = x0 - (f.value(x0) / derivative.value(x0)); 87 if (Math.abs(x1 - x0) <= absoluteAccuracy) { 88 89 setResult(x1, i); 90 return x1; 91 } 92 93 x0 = x1; 94 ++i; 95 } 96 97 throw new ConvergenceException 98 ("Maximum number of iterations exceeded " + i); 99 } 100 101 } 102 | Popular Tags |