Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created February 21, 2013 08:38
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/5003250 to your computer and use it in GitHub Desktop.
Save komasaru/5003250 to your computer and use it in GitHub Desktop.
Ruby script to calc nonlinear equation by bisection method.
# -*- coding: utf-8 -*-
#*********************************************
# 非線形方程式の解法 ( 2分法 )
#*********************************************
class NonlinearEquation
# 各種定数
EPS = 1e-08 # 打ち切り精度
LIMIT = 50 # 打ち切り回数
# 計算クラス
class Calc
# 関数定義
def f(x)
return x * x * x - x + 1
end
# 非線形方程式を解く(2分法)
def calc_nonlinear_equation
# Low, High 初期値設定
low = -2.0
high = 2.0
# 打ち切り回数 or 打ち切り誤差になるまで LOOP
@cnt_loop = 0
1.upto(LIMIT) do |k|
@cnt_loop = k
x = (low + high) / 2
if f(x) > 0
high = x
else
low = x
end
if f(x) == 0 || (high - low).abs / low.abs < EPS
printf("x=%f\n", x)
break
end
end
# 収束しなかった場合
if @cnt_loop == LIMIT
puts "収束しない"
end
end
end
# メイン処理
begin
# 計算クラスインスタンス化
obj_calc = Calc.new
# 非線形方程式を解く(2分法)
obj_calc.calc_nonlinear_equation
rescue => e
# エラーメッセージ
puts "[例外発生] #{e}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment