C++で非線形方程式を解く (ニュートン法)
非線形方程式の解法(ニュートン法)を利用して2の平方根を求める
1. まず, 関数 上の点 を考える.
2. 点 における の接線と 軸との交点 は より解に近づいている.
3. この作業を繰り返して行くことで解を求める.
点 での接線の傾きは
なので,
この式を漸化式として用いる.
#include <stdio.h> #include <math.h> double f(double x) { return x * x - 2; } double g(double x) { return 2 * x; } int main() { double low = 1; double high = 2; double x = (low + high) / 2; while (true) { double dx = x; x = x - (f(x) / g(x)); printf("%12.10f %12.10f\n", dx, x); if (fabs(x - dx) < 0.0000000001) break; } printf("%12.10f %12.10f\n", x, sqrt(2)); return 0; }
1.5000000000 1.4166666667 1.4166666667 1.4142156863 1.4142156863 1.4142135624 1.4142135624 1.4142135624 1.4142135624 1.4142135624
非線形方程式の解法(ニュートン法)を利用して2の立方根を求める
#include <stdio.h> #include <math.h> double f(double x) { return x * x * x - 2; } double g(double x) { return 3 * x * x; } int main() { double low = 1; double high = 2; double x = (low + high) / 2; while (true) { double dx = x; x = x - (f(x) / g(x)); printf("%12.10f %12.10f\n", dx, x); if (fabs(x - dx) < 0.0000000001) break; } printf("%12.10f %12.10f\n", x, cbrt(2)); return 0; }
1.5000000000 1.2962962963 1.2962962963 1.2609322247 1.2609322247 1.2599218606 1.2599218606 1.2599210499 1.2599210499 1.2599210499 1.2599210499 1.2599210499
参考文献