/* 日付を入力 * 演習6.7 * f(x) = x^2 + x - 6 の根(> 0)を2分法,ニュートン法,割線法を使って求める * プログラムを作れ.ただし,2分法,ニュートン法,割線法はそれぞれ * メソッドとし,メイン関数から呼び出してそれぞれの結果を表示 * すること.また,区間[0, 5],ε = 10E-5とする. */ public class NonlinearEquation3 { // フィールド static final double EPS = 10e-5; // メインメソッド public static void main(String [] args) { // 変数の定義 double ansBisection = 0.0; // 2分法の計算結果を入れる変数 double ansNewton = 0.0; // ニュートン法の計算結果を入れる変数 double ansDigitalNewton = 0.0; // 割線法の計算結果を入れる変数 // メソッドを使うためオブジェクトを生成 NonlinearEquation3 nonEqu = new NonlinearEquation3(); // 2分法の計算 ansBisection = nonEqu.calculateBisection(0.0, 5.0); // ニュートン法の計算 ansNewton = nonEqu.calculateNewton(5.0); // 割線法の計算 ansDigitalNewton = nonEqu.calculateDigitalNewton(5.0, 4.0); // 結果の表示 // 計算で求めた結果 System.out.println("根: " + (-1+Math.sqrt(1*1-4*1*(-6)))/(2*1)); // 2分法で求めた結果 System.out.println("2分法: " + ansBisection); // ニュートン法で求めた結果 System.out.println("ニュートン法: " + ansNewton); // 割線法で求めた結果 System.out.println("割線法: " + ansDigitalNewton); } // main // メソッドの定義 // 根を求める関数の定義 double defineFunction(double x) { return x*x + x - 6; } // 導関数の定義.ニュートン法で使用 double deriveFunction(double x) { return 2*x + 1; } // 2分法 double calculateBisection(double a, double b) { double c = 0.0; double fa; double fc; // 反復計算回数の計算 int n = (int)(Math.log((b-a)/EPS)/Math.log(2.) + 0.5); // 2分法 for (int i=0; i = x - 凅 x -= dx; if (Math.abs(dx/x) < EPS) break; // 収束判定 } return x; } // calculateNewton // 割線法 double calculateDigitalNewton(double x1, double x2) { // dx: xの差分凅を代入する変数,dy: yの差分凉を代入する変数 double dx=0.0; double dy=0.0; while (true) { // 差分商の分母 凅 dx = x1 - x2; // 差分商の分子 凉 dy = defineFunction(x1) - defineFunction(x2); // 次の x へ移動 x1 = x2; // 割線法の計算 x = x - (f(x)・凅/凉) x2 = x1 - (defineFunction(x1) * dx/dy); if (Math.abs(dx/x1) < EPS) break; // 収束判定 } return x2; } // calculateDigitalNewton } // class NonlinearEquation