/*
[1] 授業単元：数理
[2] 問題文(含コード&amp;amp;リンク)：
f(x)=cosx-x^2=0の近似解をニュートン法を用いて求めるプログラムを作成し、
以下を実行せよ。
x0 = 1(n = 0) から始めたときの xn+1 の値を求めよ。
|xn+1 － xn| / (|xn |)<10^(-6)を満たすまで実行し
(この条件を満たさない場合は30回実行し)、
各回のxn+1 の値を表にまとめろ。
[3] 環境
　[3.1] OS：Linux
　[3.3] 言語： どちらでも可
[4] 期限：2013年10月30日am9:00まで
[5] その他の制限： 特にありません。
*/

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double f(double x) { return cos(x) - x * x; }
double df(double x) { return -sin(x) - 2 * x; }
int main()
{
    double x = 1;
    cout << "+----+----------------+" << endl;
    cout << "|  n |      x_n+1     |" << endl;
    cout << "+----+----------------+" << endl;
    //         99   -9.999999e+999
    //              -999999.999999
    for (int n = 0; n < 30; n++) {
        double x_new = x - f(x) / df(x);
        cout << "| " << setw(2) << n << " | " << setw(14) << setprecision(7);
        double abs_x_new = fabs(x_new);
        if (0.1 <= abs_x_new && abs_x_new <= 999999.999999)
            cout << fixed;
        else
            cout << scientific;
        cout << x_new << " |" << endl;
        if (fabs(x_new - x) / x < 1e-6)
            break;
        x = x_new;
    }
    cout << "+----+----------------+" << endl;
    return 0;
}
