Created
February 21, 2013 08:35
-
-
Save komasaru/5003229 to your computer and use it in GitHub Desktop.
Ruby script to calc nonlinear equation by newtown 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
# -*- coding: utf-8 -*- | |
#********************************************* | |
# 非線形方程式の解法 ( ニュートン法 ) | |
#********************************************* | |
class NonlinearEquationNewton | |
# 各種定数 | |
EPS = 1e-08 # 打ち切り精度 | |
LIMIT = 50 # 打ち切り回数 | |
# 計算クラス | |
class Calc | |
# 関数定義 | |
def f(x) | |
return x * x * x - x + 1 | |
end | |
# f(x) の x における傾き ( f(x) を1回微分 ) | |
def g(x) | |
return 3 * x * x - 1 | |
end | |
# 非線形方程式を解く(ニュートン法) | |
def calc_nonlinear_equation | |
# x 初期値設定 | |
x = -2.0 | |
# 打ち切り回数 or 打ち切り誤差になるまで LOOP | |
@cnt_loop = 0 | |
1.upto(LIMIT) do |k| | |
@cnt_loop = k | |
dx = x | |
x = x - f(x) / g(x) | |
if (x - dx).abs / dx.abs < EPS | |
printf("x=%f\n", x) | |
break | |
end | |
end | |
# 収束しなかった場合 | |
if @cnt_loop == LIMIT | |
puts "収束しない" | |
end | |
end | |
end | |
# メイン処理 | |
begin | |
# 計算クラスインスタンス化 | |
obj_calc = Calc.new | |
# 非線形方程式を解く(ニュートン法) | |
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