fork(4) download
  1. /*
  2. [1] 授業単元:数理
  3. [2] 問題文(含コード&リンク):
  4. f(x)=cosx-x^2=0の近似解をニュートン法を用いて求めるプログラムを作成し、
  5. 以下を実行せよ。
  6. x0 = 1(n = 0) から始めたときの xn+1 の値を求めよ。
  7. |xn+1 - xn| / (|xn |)<10^(-6)を満たすまで実行し
  8. (この条件を満たさない場合は30回実行し)、
  9. 各回のxn+1 の値を表にまとめろ。
  10. [3] 環境
  11.  [3.1] OS:Linux
  12.  [3.3] 言語: どちらでも可
  13. [4] 期限:2013年10月30日am9:00まで
  14. [5] その他の制限: 特にありません。
  15. */
  16.  
  17. #include <iostream>
  18. #include <iomanip>
  19. #include <cmath>
  20. using namespace std;
  21. double f(double x) { return cos(x) - x * x; }
  22. double df(double x) { return -sin(x) - 2 * x; }
  23. int main()
  24. {
  25. double x = 1;
  26. cout << "+----+----------------+" << endl;
  27. cout << "| n | x_n+1 |" << endl;
  28. cout << "+----+----------------+" << endl;
  29. // 99 -9.999999e+999
  30. // -999999.999999
  31. for (int n = 0; n < 30; n++) {
  32. double x_new = x - f(x) / df(x);
  33. cout << "| " << setw(2) << n << " | " << setw(14) << setprecision(7);
  34. double abs_x_new = fabs(x_new);
  35. if (0.1 <= abs_x_new && abs_x_new <= 999999.999999)
  36. cout << fixed;
  37. else
  38. cout << scientific;
  39. cout << x_new << " |" << endl;
  40. if (fabs(x_new - x) / x < 1e-6)
  41. break;
  42. x = x_new;
  43. }
  44. cout << "+----+----------------+" << endl;
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
+----+----------------+
|  n |      x_n+1     |
+----+----------------+
|  0 |      0.8382184 |
|  1 |      0.8242419 |
|  2 |      0.8241323 |
|  3 |      0.8241323 |
+----+----------------+