2018-10-24 15:15:50 +00:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
import math
|
2018-10-25 11:49:36 +00:00
|
|
|
import cmath
|
2018-10-24 15:15:50 +00:00
|
|
|
|
|
|
|
def bailey_borwein_plouffe_pi(n):
|
2018-10-24 15:48:09 +00:00
|
|
|
"""
|
|
|
|
See https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Efficient_methods
|
|
|
|
"""
|
2018-10-24 15:15:50 +00:00
|
|
|
result = 0
|
|
|
|
for k in range(n):
|
|
|
|
result += (1/16)**k * ( 4/(8*k + 1) - 2/(8*k + 4) - 1/(8*k + 5) - 1/(8*k + 6))
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
if( __name__ == "__main__"):
|
|
|
|
|
|
|
|
assert bailey_borwein_plouffe_pi(1000) == math.pi
|
2018-10-24 15:46:55 +00:00
|
|
|
|
|
|
|
# Please note that the ``is`` operator checks wether the
|
|
|
|
# two references are the same object, basically by comparing
|
|
|
|
# their pointers.
|
|
|
|
#
|
|
|
|
# The ``==`` operator accesses the ``__eq__`` method of the
|
|
|
|
# object that *compares* the other object to itself.
|
|
|
|
#
|
|
|
|
# Because ``a/b`` **cannot** return the same object as ``math.pi``,
|
|
|
|
# the latter was created when the module ``math`` was initialized,
|
|
|
|
# this will **always** evaluate to False.
|
2018-10-25 11:49:36 +00:00
|
|
|
|
|
|
|
# As it turns out there is also the ``float.as_integer_ratio``.
|
|
|
|
# Now I kind of assume that this exercise aims torward this crap.
|
|
|
|
# You can use this method to construct two integers that are a
|
|
|
|
# fractional representation of the float.
|
|
|
|
#
|
|
|
|
# I doubt very much that there is a use case for this crap.
|
|
|
|
# There is the built-in module ``decimal`` that provides
|
|
|
|
# a proper way of dealing with floating point arithmetics,
|
|
|
|
# rounding and precision.
|
|
|
|
|
|
|
|
a,b = math.pi.as_integer_ratio()
|
|
|
|
assert a/b == math.pi
|