8. วัตถุสิ่งของ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 8-20  โปรแกรมหารากของฟังก์ชัน f(x) = x3 + 1 ด้วยวิธีของนิวตัน
import java.util.Scanner;
public class NewtonMethod {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("initial real = ");
    double r = kb.nextDouble();
    System.out.print("initial imag = ");
    double i = kb.nextDouble();
    Complex root = findRoot(new Complex(r, i));
    System.out.println(root);
  }
  public static Complex findRoot(Complex z1) {
    Complex z0;
    do {
      z0 = z1;
      z1 = z0.substract(f(z0).divide(df(z0)));
    } while (z1.substract(z0).abs() > 1e-10);
    return z1;
  }
  private static Complex f(Complex z) {
    return z.multiply(z).multiply(z).substract(1);
  }
  private static Complex df(Complex z) {
    return z.multiply(z).multiply(3);
  }
}
©2009 S.Prasitjutrakul