ニュートン法 | spin on the RITZ

ニュートン法

久しぶりにJava


『どうやって小数入力するんだよ・・・・』


ってなったのはナイショ




ニュートン法で近似解を求めるプログラム


Newthon.java

import java.io.*;

public class Newthon {
    public static void main(String[] args) {
        double x1 = 0.0;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.print("初期値を入力 -> ");
            String line = reader.readLine();
            x1 = Double.parseDouble(line);
        } catch (IOException e) {
            System.out.println(e);
        }
        Newthon(x1);
    }
    //f(x)
    public static double f(double x) {
        return x * x - 4.0;
    }
    //f'(x)
    public static double df(double x) {
        return 2 * x;
    }
    //ニュートン法
    public static void Newthon(double x1) {
        double EPS = 1.0e-5;
        double x2;
        int max_cnt = 1000;
        int cnt = 0;

        while (true) {
            x2 = x1 - f(x1) / df(x1);
            if (-EPS < (x2-x1) && (x2-x1) < EPS) {
                System.out.println("近似解 : " + x2);
                break;
            }
            if (cnt == max_cnt) {
                System.out.println("近似解が得られませんでした");
                break;
            }
            x1 = x2;
            cnt++;
        }
    }
}