Python
from __future__ import division
from itertools import count, izip, repeat, chain, tee, islice
def flatten(iterable):
"Flatten one level of nesting."
return chain.from_iterable(iterable)
def multiply(iterable, scalar):
"Multiply each element of an iterable by a scalar."
for e in iterable:
yield e * scalar
def subtract(iterable1, iterable2):
"Pair-wise difference of two iterables."
for e, f in izip(iterable1, iterable2):
yield e - f
def add(iterable1, iterable2):
"Pair-wise sum of two iterables."
for e, f in izip(iterable1, iterable2):
yield e + f
def sum_limit(iterable, stop = 1000000):
"Partial sum limit of an iterable, up to `stop' terms."
p_sum = 0 # current partial sum
t_sum = 0 # total of partial sums
for e in islice(iterable, stop):
p_sum += e
t_sum += p_sum
# return average of partial sums
return t_sum / stop
# All natural numbers
n = count(1)
# The same range multiplied by 4
n4 = multiply(count(1), 4)
# Interspersing with zeros won't change the sum
n4 = flatten(izip(repeat(0), n4))
# Subtracting 4n - n results in 3n
n3 = subtract(n4, n)
# Make two clones of this range
n3a, n3b = tee(n3)
# Double the range, by adding it to itself
# This is now 6n
n6 = add(n3a, chain([0], n3b))
# Partial sum limit of the above
# Take 1000000 values, should be enough to converge
limit = sum_limit(n6, 1000000)
# Divide by 6 to get the sum limit of n
print limit / 6
結果:
-0.0833333333333
だから、トリックは何ですか?
秘isは、これが有効な計算であるということです。