Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 04:42
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/784d9d3de9f11de64191eede57989d96 to your computer and use it in GitHub Desktop.
Save komasaru/784d9d3de9f11de64191eede57989d96 to your computer and use it in GitHub Desktop.
Ruby script to compute nonlinear equation with bisection method.
#! /usr/local/bin/ruby
#*********************************************
# 非線形方程式の解法 ( 2分法 )
#*********************************************
class NonlinearEquation
# 各種定数
EPS = 1e-08 # 打ち切り精度
LIMIT = 50 # 打ち切り回数
def initialize
# 関数定義
@f = lambda { |x| x**3 - x + 1 }
end
# 非線形方程式を解く(2分法)
def calc_nonlinear_equation
# Low, High 初期値設定
low, high = -2.0, 2.0
# 打ち切り回数 or 打ち切り誤差になるまで LOOP
@cnt_loop = 0
1.upto(LIMIT) do |k|
@cnt_loop = k
x = (low + high) / 2
if @f.call(x) > 0
high = x
else
low = x
end
if @f.call(x) == 0 || (high - low).abs / low.abs < EPS
printf("x = %f\n", x)
break
end
end
# 収束しなかった場合
puts "収束しない" if @cnt_loop == LIMIT
end
end
if __FILE__ == $0
begin
# 計算クラスインスタンス化
obj = NonlinearEquation.new
# 非線形方程式を解く(2分法)
obj.calc_nonlinear_equation
rescue => e
$stderr.puts "[例外発生] #{e}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment