DunningKruger

pie.py

Nov 26th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | Source Code | 0 0
  1. from mpmath import mp
  2. import time
  3.  
  4. mp.dps = 2000 # working precision; adjust as you like
  5.  
  6. def compute_coeffs(m):
  7. """Compute c_{m,k} = (-1)^{m+k} * (1/k) * prod_{j!=k} j^2 / (k^2 - j^2)."""
  8. coeffs = []
  9. for k in range(1, m+1):
  10. prod = mp.mpf('1')
  11. for j in range(1, m+1):
  12. if j == k:
  13. continue
  14. prod *= (j*j) / (k*k - j*j)
  15. c = (-1)**(m+k) * (mp.mpf(1)/k) * prod
  16. coeffs.append(c)
  17. return coeffs
  18.  
  19. def step_direct(x, coeffs):
  20. """One iteration using direct sin(k*x) calls."""
  21. dx = mp.mpf('0')
  22. m = len(coeffs)
  23. for k in range(1, m+1):
  24. dx += coeffs[k-1] * mp.sin(k * x)
  25. return x + dx
  26.  
  27. def step_recur(x, coeffs):
  28. """One iteration using recurrence for sin(k*x)."""
  29. dx = mp.mpf('0')
  30. m = len(coeffs)
  31.  
  32. # compute sin(x), cos(x) once
  33. s1 = mp.sin(x) # sin(1*x)
  34. c = mp.cos(x) # cos(x)
  35.  
  36. # k = 1 term
  37. s_prev = mp.mpf('0') # sin(0*x)
  38. s_curr = s1 # sin(1*x)
  39. dx += coeffs[0] * s_curr
  40.  
  41. # k = 2..m terms via recurrence: sin(kx) = 2 cos x sin((k-1)x) - sin((k-2)x)
  42. for k in range(2, m+1):
  43. s_next = 2 * c * s_curr - s_prev
  44. dx += coeffs[k-1] * s_next
  45. s_prev, s_curr = s_curr, s_next
  46.  
  47. return x + dx
  48.  
  49. # --------- experiment parameters ---------
  50.  
  51. m = 30 # try 2, 3, 5, 10, 20, ...
  52. N = 1000 # number of iterations in the timing loop
  53.  
  54. coeffs = compute_coeffs(m)
  55.  
  56. # sanity check: direct and recur match for a single step
  57. x0 = mp.mpf(3)
  58. y_direct = step_direct(x0, coeffs)
  59. y_recur = step_recur(x0, coeffs)
  60. print("Sanity check diff:", y_direct - y_recur)
  61.  
  62. # --- time direct version ---
  63. x = mp.mpf(3)
  64. t0 = time.perf_counter()
  65. for _ in range(N):
  66. x = step_direct(x, coeffs)
  67. t1 = time.perf_counter()
  68. print(f"direct time (m={m}, N={N}): {t1 - t0:.6f} s")
  69.  
  70. # --- time recurrence version ---
  71. x = mp.mpf(3)
  72. t2 = time.perf_counter()
  73. for _ in range(N):
  74. x = step_recur(x, coeffs)
  75. t3 = time.perf_counter()
  76. print(f"recur time (m={m}, N={N}): {t3 - t2:.6f} s")
  77.  
  78. # show final approximation (optional)
  79. print("Final x (recur):", mp.nstr(x, 50))
  80.  
Advertisement
Add Comment
Please, Sign In to add comment