/mycila-math/trunk/todo/java/IntroductiontoProgramminginJava/Newton.java

http://mycila.googlecode.com/ · Java · 31 lines · 15 code · 6 blank · 10 comment · 2 complexity · edce37ede06dd3709f8a75ff7a494784 MD5 · raw file

  1. /*************************************************************************
  2. * Compilation: javac Newton.java
  3. * Execution: java Newton
  4. *
  5. * Run Newton's method to finds the roots and local min/max of
  6. * a twice-differentiable function of one variable.
  7. *
  8. *************************************************************************/
  9. public class Newton {
  10. public static final double EPSILON = 1e-14;
  11. // Newton's method to find x* such that f(x*) = 0, starting at x
  12. public static double root(Function f, double x) {
  13. while (Math.abs(f.eval(x) / f.deriv(x)) > EPSILON) {
  14. x = x - f.eval(x) / f.deriv(x);
  15. }
  16. return x;
  17. }
  18. // Newton's method to find x* such that f'(x*) = 0, starting at x
  19. public static double optimum(Function f, double x) {
  20. while (Math.abs(f.deriv(x) / f.deriv2(x)) > EPSILON) {
  21. x = x - f.deriv(x) / f.deriv2(x);
  22. }
  23. return x;
  24. }
  25. }