Last active
April 19, 2018 04:39
-
-
Save komasaru/9b70c07f46cf266dd20e2cfde3ddc313 to your computer and use it in GitHub Desktop.
Ruby script to compute Taylor expansion (cos(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 | |
#********************************************* | |
# テイラー展開 [ cos(x) ] | |
#********************************************* | |
class TaylorExpansionCos | |
# 各種定数 | |
EPS = 1e-08 # 精度 | |
PI = 3.1415926535 # 円周率 | |
# テイラー展開 | |
def calc_taylor | |
# ラジアン値計算 | |
rd = PI / 180 | |
# x = 0 から 180 を 10 刻みで計算 | |
puts " x mycos(x) cos(x)" | |
0.step(180, 10) do |x| | |
printf("%5.1f%14.6f%14.6f\n", x, calc_cos(x * rd), Math.cos(x * rd)) | |
end | |
end | |
# Cos 計算 | |
def calc_cos(x) | |
# 変数初期化 | |
d = s = e = 1.0 | |
# x の値が 0 から 2π の範囲外の場合、0 から 2π に収める | |
x = x % (2 * PI) | |
# 最大200回ループ処理 | |
# ( ただし、偶数項は 0 なので除外 ) | |
1.step(200, 2) do |k| | |
d = s # d 和 | |
e *= -x * x / (k * (k + 1)) # 各項の値 | |
s += e # s 和 | |
# 打ち切り誤差 | |
return s if (s - d).abs / d.abs < EPS | |
end | |
# 収束しない時 | |
return 9999.0 | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = TaylorExpansionCos.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