fork(1) download
  1. import numpy as np
  2.  
  3. #ガウス=ルジャンドルのアルゴリズム。N回繰り返す
  4. def GaussRegendre(N):
  5. #初項
  6. a = 1.0
  7. b = np.sqrt(2) / 2
  8. t = 1 / 4
  9. p = 1
  10.  
  11. for i in range(N): #iが0からN-1までの間以下を繰り返す
  12. #漸化式に従い、次の項を計算
  13. a_new = (a + b) / 2
  14. b_new = np.sqrt(a * b)
  15. t_new = t - p * (a - a_new)**2
  16. p_new = 2 * p
  17.  
  18. #古い値を新しい値に置き換え
  19. a = a_new
  20. b = b_new
  21. t = t_new
  22. p = p_new
  23.  
  24. pi = (a + b)**2 / (4 * t) #円周率の計算
  25. return pi
  26.  
  27. #出力
  28. print("GaussRegendre(1) = " + str(GaussRegendre(1)))
  29. print("GaussRegendre(2) = " + str(GaussRegendre(2)))
  30. print("GaussRegendre(3) = " + str(GaussRegendre(3)))
Success #stdin #stdout 0.15s 28568KB
stdin
Standard input is empty
stdout
GaussRegendre(1) = 3.1405792505221686
GaussRegendre(2) = 3.141592646213543
GaussRegendre(3) = 3.141592653589794