Created
February 21, 2013 08:40
-
-
Save komasaru/5003260 to your computer and use it in GitHub Desktop.
Ruby script to calc taylor expansion of cos.
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 -*- | |
#********************************************* | |
# テイラー展開 [ cos(x) ] | |
#********************************************* | |
class TaylorExpansionCos | |
# 各種定数 | |
EPS = 1e-08 # 精度 | |
PI = 3.1415926535 # 円周率 | |
# 計算クラス | |
class Calc | |
# テイラー展開 | |
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 = -e * x * x / (k * (k + 1)) # 各項の値 | |
s += e # s 和 | |
# 打ち切り誤差 | |
if (s - d).abs / d.abs < EPS | |
return s | |
end | |
end | |
# 収束しない時 | |
return 9999.0 | |
end | |
end | |
# メイン処理 | |
begin | |
# 計算クラスインスタンス化 | |
obj_calc = Calc.new | |
# テイラー展開 | |
obj_calc.calc_taylor | |
rescue => e | |
# エラーメッセージ | |
puts "[例外発生] #{e}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment