Created
August 7, 2015 04:55
-
-
Save junpeitsuji/e243350b2ba6f2da0424 to your computer and use it in GitHub Desktop.
超幾何級数を計算するスクリプト
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
# hypergeometric.rb | |
# 超幾何級数を計算するスクリプト | |
# | |
require 'rational' | |
# ポッホハマー記号 (x)_n を計算する | |
def pochhammer x, n | |
if n == 0 then | |
return 1 | |
else | |
prod = 1 | |
n.times do |k| | |
prod *= (x + k) | |
end | |
return prod | |
end | |
end | |
# 整数 x に対する Gamma(x) を計算する | |
def gamma x | |
# (x-1)! を計算する | |
if x == 1 | |
return 1 | |
else | |
prod = 1 | |
(x-1).times do |k| | |
prod *= (k+1) | |
end | |
return prod | |
end | |
end | |
# 超幾何定理により F(a, b, c; 1) を計算する | |
def f(a, b, c) | |
if a < 0 then | |
# a < 0 の場合はヴァンデルモンドの恒等式を用いる | |
n = -a | |
p = pochhammer(c-b, n) | |
q = pochhammer(c, n) | |
Rational(p, q) | |
else | |
p = gamma(c) * gamma(c - a - b) | |
q = gamma(c-a) * gamma(c-b) | |
Rational(p, q) | |
end | |
end | |
# 超幾何級数 f(a, b, c; z) における z^n の係数を配列で求める | |
def f_coef(a, b, c) | |
array = [] | |
10.times do |n| | |
p = pochhammer(a, n) * pochhammer(b, n) | |
q = pochhammer(c, n) * gamma(n+1) | |
a_n = Rational(p, q) | |
array.push a_n | |
end | |
array | |
end | |
# 有理数 num を tex 形式の文字列に変換 | |
def num_to_tex num | |
p = num.numerator | |
q = num.denominator | |
str = "" | |
if q != 1 then | |
str += "\\frac\{#{p}\}\{\\\;#{q}\\\;\}" | |
else | |
str += "#{p}" | |
end | |
str | |
end | |
# 係数配列 array を tex 形式の文字列に変換 | |
def array_to_tex array | |
str = "" | |
array.each do |a_n| | |
p = a_n.numerator | |
q = a_n.denominator | |
if q != 1 then | |
str += "\\frac\{#{p}\}\{#{q}\} + " | |
else | |
str += "#{p} + " | |
end | |
end | |
str += "\\cdots" | |
str | |
end | |
# 以下の条件 | |
# a ∈ Z, b ∈ Z, c ∈ Z, | |
# a + b < c, | |
# c > 0 | |
# の範囲で a, b, c を選んで計算する | |
#=begin | |
# テストケース1 | |
a = 1 | |
b = 1 | |
c = 4 | |
#=end | |
=begin | |
# テストケース2 | |
a = 1 | |
b = 2 | |
c = 14 | |
=end | |
=begin | |
# テストケース3 | |
a = 1 | |
b = 1 | |
c = 3 | |
=end | |
# tex 形式で出力 | |
puts num_to_tex( f(a, b, c) ) + " = " + array_to_tex( f_coef(a, b, c) ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment