Last active
April 19, 2018 04:40
-
-
Save komasaru/eb76cf9de8d852f6e1711e049965c510 to your computer and use it in GitHub Desktop.
Ruby script to compute Taylor expansion (exp(x)).
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 | |
#********************************************* | |
# テイラー展開 [ exp(x) ] | |
#********************************************* | |
class TaylorExpansion | |
# 各種定数 | |
EPS = 1e-08 # 精度 | |
# テイラー展開 | |
def calc_taylor | |
# x = -50 から 50 を 10 刻みで計算 | |
puts " x myexp(x) exp(x)" | |
-50.step(50, 10) do |x| | |
printf("%5.1f%14.6g%14g\n", x, calc_exp(x), Math.exp(x)) | |
end | |
end | |
# Exp 計算 | |
def calc_exp(x) | |
# 変数初期化 | |
d = s = e = 1.0 | |
# 最大200回ループ処理 | |
1.upto(200) do |k| | |
d = s # d 和 | |
e = e * x.abs / k # e 値 | |
s += e # s 和 | |
# 打ち切り誤差 | |
return x > 0 ? s : 1.0 / s if (s - d).abs / d.abs < EPS | |
end | |
# 収束しない時 | |
return 0.0 | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = TaylorExpansion.new | |
# テイラー展開 | |
obj.calc_taylor | |
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