0

I got stuck and I don't know how to find how many iterations are needed for Newton's method. Where should I put it? Should I put it in a while loop?

tolerance = 10e-6

def newton(funkcia,derivacia,x):

  def f(x):
      f=eval(funkcia) #precita mi string a prehodi to na rovnicu s variables
      return f #zapamataj si vysledok=return, aby sme ho mohli dalej pouzit

  def df(x):
      df=eval(derivacia)
      return df

  while f(x) < -tolerance or f(x) > tolerance: #dopln pocet interacii
      x=x-(f(x)/df(x)) #vzorec{}

  print(f"koren je v bode {x}")
      
newton("x**2 - 2","2*x", 20 ) 
BSMP
  • 4,596
  • 8
  • 33
  • 44
  • It's not the function value you compare to the tolerance, it's the difference between the previous and current value of `x`. Intuitively, you run the code until `f(x)/df(x)` returns `x` (or something close enough to it). – chepner Nov 01 '21 at 13:22
  • @chepner close to the end f(x)/df(x) will be close to 0, not x – Yaroslav Kornachevskyi Nov 01 '21 at 13:28
  • 1
    It is ok to test f(x) to tolerance, just use abs(f(x)) > tolerance. Also you may check number of iterations - if it is more then 100 or even 10, then initial value is not selected correctly. – Yaroslav Kornachevskyi Nov 01 '21 at 13:31
  • 1
    So answer is: number of iterations is not required for this method. It could be used only to stop method if it diverges (too much iterations passed, but f(x) is still far from 0. – Yaroslav Kornachevskyi Nov 01 '21 at 13:33

0 Answers0