C++ source code to compute nonlinear equation with bisection method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************* | |
* 非線形方程式の解法 ( 2分法 ) | |
*********************************************/ | |
#include <iostream> // for cout | |
#include <math.h> // for fabs() | |
#include <stdio.h> // for printf() | |
// 方程式定義 | |
#define f(x) (x * x * x - x + 1) | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
// 各種定数 | |
static const double eps = 1e-08; // 打ち切り精度 | |
static const int limit = 50; // 打ち切り回数 | |
// 各種変数 | |
double low, high, x; // Low, High, x 値 | |
int k; // LOOP インデックス | |
public: | |
// 非線形方程式を解く(2分法) | |
void calcNonlinearEquation(); | |
}; | |
/* | |
* 非線形方程式を解く(2分法) | |
*/ | |
void Calc::calcNonlinearEquation() | |
{ | |
// Low, High 初期値設定 | |
low = -2.0; | |
high = 2.0; | |
// 打ち切り回数 or 打ち切り誤差になるまで LOOP | |
for (k = 1; k <= limit; k++) { | |
x = (low + high) / 2; | |
if (f(x) > 0) | |
high = x; | |
else | |
low = x; | |
if (f(x) == 0 || fabs(high - low) / fabs(low) < eps) { | |
printf("x=%f\n", x); | |
break; | |
} | |
} | |
// 収束しなかった場合 | |
if (k > limit) | |
cout << "収束しない" << endl; | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
try | |
{ | |
// 計算クラスインスタンス化 | |
Calc objCalc; | |
// 非線形方程式を解く(2分法) | |
objCalc.calcNonlinearEquation(); | |
} | |
catch (...) { | |
cout << "例外発生!" << endl; | |
return -1; | |
} | |
// 正常終了 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment