iteration.py

#
# Simple iterative method 
# Vincent Legat - 2018
# Ecole Polytechnique de Louvain
#

# =========================================================================

def iter(x,tol,nmax,g):
  n = 0; delta = float("inf")
  while abs(delta) > tol and n < nmax :
    n = n + 1
    xold = x
    x = g(x)
    delta = xold - x
    print(" x = %21.14e (%d)" % (x,n))
  return x

# ============================= mainProgram ===============================

g = lambda x : (x**3 + 1)/3

print("Found x = ", iter(0.0,10e-3,50,g))
print("Found x = ", iter(1.5,10e-3,50,g))
print("Found x = ", iter(2.0,10e-3,50,g))

# =========================================================================