Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active December 1, 2017 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/5ed02cbd105a2948900a5b8da2b4a38e to your computer and use it in GitHub Desktop.
Save komasaru/5ed02cbd105a2948900a5b8da2b4a38e to your computer and use it in GitHub Desktop.
C++ source code to compute nonlinear equation with bisection method.
/*********************************************
* 非線形方程式の解法 ( 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