Ruby script to expand Fourier's series.
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 | |
#********************************************* | |
# フーリエ級数展開 | |
# f(t) = -1 (-pi < t <= 0 ) | |
# 1 ( 0 < t <= pi) | |
#********************************************* | |
# | |
class FourierSeriesExpansion | |
N = 3 # 計算項数 | |
# フーリエ級数展開 | |
def expand_fourier_series | |
open("FourierSeriesExpansion.csv", "w") do |f| | |
# ヘッダ出力 | |
f.puts "t,f(t)" | |
# 1 / 1000 刻みで計算 | |
y = 0 | |
((Math::PI * -1000).truncate).upto(Math::PI * 1000) do |t| | |
1.upto(N) { |i| y += calc_term(i, t / 1000.0) } | |
f.puts "%.3f,%.6f" % [t / 1000.0, 4 / Math::PI * y] | |
y = 0 | |
end | |
end | |
rescue => e | |
raise | |
end | |
private | |
# 各項計算 | |
def calc_term(n, t) | |
return Math::sin((2 * n - 1) * t) / (2 * n - 1) | |
rescue => e | |
raise | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = FourierSeriesExpansion.new | |
# フーリエ級数展開 | |
obj.expand_fourier_series | |
rescue => e | |
$stderr.puts "[#{e.class}] #{e.message}" | |
e.backtrace.each{ |tr| $stderr.puts "\t#{tr}" } | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment