Created
February 21, 2013 08:41
-
-
Save komasaru/5003271 to your computer and use it in GitHub Desktop.
Ruby script to calc taylor expansion of exp(x).
This file contains hidden or 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 -*- | |
| #********************************************* | |
| # テイラー展開 [ exp(x) ] | |
| #********************************************* | |
| class TaylorExpansion | |
| # 各種定数 | |
| EPS = 1e-08 # 精度 | |
| # 計算クラス | |
| class Calc | |
| # テイラー展開 | |
| def calc_taylor | |
| # x = -50 から 50 を 10 刻みで計算 | |
| puts " x myexp(x) exp(x)" | |
| -50.step(50, 10) do |x| | |
| printf("%5.1f%14.6g%14.6g\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 和 | |
| # 打ち切り誤差 | |
| if (s - d).abs / d.abs < EPS | |
| if x > 0 | |
| return s | |
| else | |
| return 1.0 / s | |
| end | |
| end | |
| end | |
| # 収束しない時 | |
| return 0.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