############################################
# セカント法による exp(x)-3x=0 の根
# coded by Y.Suganuma
############################################
############################################
# secant法(はさみうち法)による非線形方程式f(x)=0の解
# x1,x2 : 初期値(x1 < x2)
# max : 最大試行回数
# eps1 : 終了条件1(|x(k+1)-x(k)|<eps1)
# eps2 : 終了条件2(|f(x(k))|<eps2)
# ind : > 0 : 収束回数
# =-1 : 収束しなかった
# fn : f(x)を計算する関数名
# return : 解
# coded by Y.Suganuma
############################################
def secant(x1, x2, max, eps1, eps2, ind, &fn)
x = 0.0
count = 0
ind[0] = 0
f1 = fn.call(x1)
f2 = fn.call(x2)
if f1.abs() < eps2
x = x1
else
if f2.abs() < eps2
x = x2
else
while ind[0] == 0
count += 1
if (f2-f1).abs() < eps2
ind[0] = -1
else
x = x2 - f2 * (x2 - x1) / (f2 - f1)
f = fn.call(x)
if f.abs() < eps2 or (x2-x1).abs() < eps1 or (x2-x1).abs() < eps1*x2.abs()
ind[0] = count
else
if count < max
if f1*f2 < 0.0
x2 = x
f2 = f
else
x1 = x
f1 = f
end
else
ind[0] = -1
end
end
end
end
end
end
return x
end
################
# 関数値の計算 #
################
snx = Proc.new { |x|
Math.exp(x) - 3.0 * x
}
# データの設定
ind = [0];
eps1 = 1.0e-10
eps2 = 1.0e-10
max = 100
x1 = 0.0
x2 = 1.0
# 実行と結果
x = secant(x1, x2, max, eps1, eps2, ind, &snx)
print(" ind=", ind[0], " x=", x, " f= ", snx.call(x), "\n")