Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Newton.py
- # sin(x)=0 ,Nollakohta Newton-iteroinnilla --> Pi
- # Juhani Kaukoranta 17.3.2022, kieliposkella...;-)
- import gmpy2 # käytetään Pythonin rajattoman tarkkuuden kirjastoa
- import math
- from gmpy2 import mpfr # rajattoman tarkkuuden liukuluvut
- tarkkuus10=101 # 100 desimaalinumeroa
- tarkkuusbits = int(tarkkuus10*math.log2(10)) # tarkkuus bitteinä
- gmpy2.get_context().precision=tarkkuusbits+1 # tarkkuus 332 bit = 100 desimaalinumeroa
- def Newton(x0):
- epsilon = 1/10**tarkkuus10 # vastauksen tarkkuus
- h = 1/10**(tarkkuus10-2) # derivaatan numeerista laskemista varten /f(x+h)-f(h))/h
- f = lambda x: gmpy2.sin(x) # funktio, jonka nollakohta etsitään
- xold = mpfr(str(x0)) # alkuarvo
- while True:
- fold = f(xold)
- xnew = xold - h*fold/(f(xold+h)-fold) # x(n+1) = x(n)- f(x(n))/f '(x(n))
- if abs(xnew - xold) < epsilon:
- return xnew
- xold = xnew
- # Piin alkuarvoksi Newton-iteroinnissa raamatullinen 3.0
- print("Pii ",tarkkuus10," desimaalia = ",Newton(3.0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement