Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/5516410 to your computer and use it in GitHub Desktop.
Save komasaru/5516410 to your computer and use it in GitHub Desktop.
Ruby script to expand Fourier's series.
#! /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