Last active
April 19, 2018 04:41
-
-
Save komasaru/1f7f5ec2e204d84f43bd988de082fba5 to your computer and use it in GitHub Desktop.
Ruby script to compute nonlinear equation with Newton 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
#! /usr/local/bin/ruby | |
#********************************************* | |
# 非線形方程式の解法 ( ニュートン法 ) | |
#********************************************* | |
class NonlinearEquationNewton | |
# 各種定数 | |
EPS = 1e-08 # 打ち切り精度 | |
LIMIT = 50 # 打ち切り回数 | |
def initialize | |
# 関数定義 | |
@f = lambda { |x| x**3 - x + 1 } | |
# f(x) の x における傾き ( f(x) を1回微分 ) | |
@g = lambda { |x| 3 * x**2 - 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 -= @f.call(x) / @g.call(x) | |
if (x - dx).abs / dx.abs < EPS | |
printf("x = %f\n", x) | |
break | |
end | |
end | |
# 収束しなかった場合 | |
puts "収束しない" if cnt_loop == LIMIT | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = NonlinearEquationNewton.new | |
# 非線形方程式を解く(ニュートン法) | |
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