pyzuki

The Euler Series

Aug 10th, 2011
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. # "The Euler Series" p.31 in "The Pleasures of Pi,e"
  2.  
  3. # 1/1**2 + 1/2**2 + 2/3**2 + ... + 1/n**2 + ... = pi**/6 (limit)  (very slow to converge)
  4.  
  5. # So I use Hans Lundmark's post on http://math.stackexchange.com, at
  6. # http://math.stackexchange.com/questions/8337/different-methods-to-compute-sum-n-1-infty-frac1n2
  7.  
  8. from mpmath import *; mp.dps = 100; mp.pretty = True
  9.  
  10. def compareSequences(seq1, seq2):
  11.     """
  12.    Returns first index at which two sequences differ
  13.  
  14.    >>> seq1 = "Now is the time"
  15.    >>> seq2 = "Now was the time"
  16.    >>> compareSequences(seq1, seq2)
  17.    4
  18.    """
  19.     for index in range(len(seq2)):
  20.         if seq1[index] != seq2[index]:
  21.             return index
  22.     return None
  23.  
  24. def int_commas(n):
  25.     """
  26.    inserts commas into integers and returns the string
  27.  
  28.    E.g. -12345678 -> -12,345,789
  29.    """
  30.     return format(n, ',d')
  31.  
  32.  
  33.  
  34. n = mpf(150)
  35. print("n =", int_commas(int(n)))
  36.  
  37. print()
  38. limit = (pi()**mpf(2))/mpf(6)
  39. upper_bound_partial_sum = (mpf(2)*(4**n - 1)/mpf(3)) * (pi()**mpf(2)/(4**(n+1)))
  40. idx1 = compareSequences(str(upper_bound_partial_sum), str(limit))
  41.  
  42. lower_bound_partial_sum = (mpf(2)*(4**n - 1)/mpf(3) - (mpf(2)**n - 1)) * (pi()**mpf(2)/(4**(n+1)))
  43. idx2 = compareSequences(str(lower_bound_partial_sum), str(limit))
  44.  
  45. print(limit, "limit (PI**2/6)")
  46. print((idx1-1)*' ', '^')
  47. print(upper_bound_partial_sum, "upper_bound_partial_sum")
  48. print()
  49. print()
  50. print(limit, "limit (PI**2/6)")
  51. print((idx2-1)*' ', '^')
  52. print(lower_bound_partial_sum, "lower_bound_partial_sum")
  53.  
  54. """
  55. OUTPUT
  56. n = 150
  57.  
  58. 1.644934066848226436472415166646025189218949901206798437735558229370007470403200873833628900619758705 limit (PI**2/6)
  59.                                                                                         ^
  60. 1.644934066848226436472415166646025189218949901206798437735558229370007470403200873833628899812245197 upper_bound_partial_sum
  61.  
  62.  
  63. 1.644934066848226436472415166646025189218949901206798437735558229370007470403200873833628900619758705 limit (PI**2/6)
  64.                                            ^
  65. 1.644934066848226436472415166646025189218949899478015751393061460363041277434208815632129055954370542 lower_bound_partial_sum
  66. """
Advertisement
Add Comment
Please, Sign In to add comment