Advertisement
talesrm

Untitled

Nov 14th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. #!-*- conding: utf8 -*-
  2. import numpy as np
  3.  
  4. if __name__ == "__main__":
  5.     def fun_Z(x):
  6.         return (x**4)+4 # Funcaoo principal
  7.     def der_Z(x):
  8.         return 4*(x**3) # Derivada da funcao principal
  9.  
  10. def newton(fun_Z, der_Z, x0, tolerancia, iteracoes=20): # Metodo de Newton
  11.     x1 = 0
  12.  
  13.     if abs(x0-x1) <= tolerancia and abs((x0-x1)/x0) <= tolerancia:
  14.         return x0
  15.  
  16.     print("k\t x0\t\t Funcao(x0)")
  17.     k = 1
  18.  
  19.     while k <= iteracoes:
  20.         x1 = x0 - (fun_Z(x0)/der_Z(x0))
  21.         print("x%d\t%e\t%e"%(k,x1,fun_Z(x1)))
  22.  
  23.         if abs(x0-x1)<= tolerancia and abs((x0-x1)/x0)<= tolerancia:
  24.             plt.plot(x0, fun_Z(x0), 'or')
  25.             return x1
  26.         x0 = x1
  27.         k = k + 1
  28.  
  29.         # Para o programa quando o numero de iteracoes excede o permitido.
  30.         if k > iteracoes:
  31.             print("ERRO: Numero maximo de iteracoes excedido")
  32.     return x1 # Retorna o valor encontrado
  33.  
  34. sqrt = newton(fun_Z, der_Z, 0.00001, 0.00001)
  35. print("O valor aproximado de Z eh: "+str(sqrt))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement