Last active
April 19, 2018 04:56
Ruby script to compute Napier's constant.
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 | |
#********************************************* | |
# ネイピア数 e (自然対数の底)計算 | |
#********************************************* | |
# | |
class CalcNapier | |
L = 1000 # 算出桁数 | |
L1 = L / 8 + 1 # 配列サイズ | |
L2 = L1 + 1 # 配列サイズ + 1 | |
N = 451 # 計算項数 | |
# 計算 | |
def compute | |
# 配列宣言・初期化 | |
s = Array.new(L2 + 1, 0) # 総和 | |
a = Array.new(L2 + 1, 0) # 各項 | |
# 計算 | |
s[0] = 1 | |
a[0] = 1 | |
1.upto(N) do |k| | |
a = long_div(a, k) | |
s = long_add(s, a) | |
end | |
# 結果出力 | |
display(s) | |
rescue => e | |
raise | |
end | |
private | |
# ロング + ロング | |
def long_add(a, b) | |
z = Array.new(N, 0) | |
carry = 0 | |
L2.downto(0) do |i| | |
z[i] = a[i] + b[i] + carry | |
if z[i] < 100000000 | |
carry = 0 | |
else | |
z[i] -= 100000000 | |
carry = 1 | |
end | |
end | |
return z | |
rescue => e | |
raise | |
end | |
# ロング / ショート | |
def long_div(a, b) | |
z = Array.new(N, 0) | |
r = 0 | |
0.upto(L2) do |i| | |
w = a[i] | |
z[i] = (w + r) / b | |
r = ((w + r) % b) * 100000000 | |
end | |
return z | |
rescue => e | |
raise | |
end | |
# 結果出力 | |
def display(s) | |
printf("%7d. ", s[0]) | |
1.upto(L1 - 1) do |i| | |
printf("%08d ", s[i]) | |
end | |
printf("\n") | |
rescue => e | |
raise | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = CalcNapier.new | |
# ネイピア数計算 | |
obj.compute | |
rescue => e | |
$stderr.puts "[#{e.class}] #{e.message}\n" | |
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