Advertisement
jukaukor

Newtoniter_pi_gmpy2.py

Mar 17th, 2022
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #Newton.py
  2. # sin(x)=0 ,Nollakohta Newton-iteroinnilla --> Pi
  3. # Juhani Kaukoranta 17.3.2022, kieliposkella...;-)
  4. import gmpy2 # käytetään Pythonin rajattoman tarkkuuden kirjastoa
  5. import math
  6. from gmpy2 import mpfr # rajattoman tarkkuuden liukuluvut
  7. tarkkuus10=101 # 100 desimaalinumeroa
  8. tarkkuusbits = int(tarkkuus10*math.log2(10)) # tarkkuus bitteinä
  9. gmpy2.get_context().precision=tarkkuusbits+1 # tarkkuus 332 bit = 100 desimaalinumeroa
  10. def Newton(x0):
  11. epsilon = 1/10**tarkkuus10 # vastauksen tarkkuus
  12. h = 1/10**(tarkkuus10-2) # derivaatan numeerista laskemista varten /f(x+h)-f(h))/h
  13. f = lambda x: gmpy2.sin(x) # funktio, jonka nollakohta etsitään
  14. xold = mpfr(str(x0)) # alkuarvo
  15. while True:
  16. fold = f(xold)
  17. xnew = xold - h*fold/(f(xold+h)-fold) # x(n+1) = x(n)- f(x(n))/f '(x(n))
  18. if abs(xnew - xold) < epsilon:
  19. return xnew
  20. xold = xnew
  21. # Piin alkuarvoksi Newton-iteroinnissa raamatullinen 3.0
  22. print("Pii ",tarkkuus10," desimaalia = ",Newton(3.0))
  23.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement