import math
import time

import numpy as np
import matplotlib.pyplot as plt

def F(x):
    return (230 * math.pow(x, 4) + 18 * math.pow(x, 3) + 9 * math.pow(x, 2) - 9) / 221

def FDiff(x):
    return (920 * math.pow(x, 3) + 54 * pow(x, 2) + 18 * x) / 221


def calcAlpha(start, stop, FDiff):
    x = np.arange(start, stop + abs(((start-stop)/100)), abs(((start-stop)/100)))
    y = [FDiff(x_value) for x_value in x]
    ymax = max(y)
    return ymax

def iteration(x0, startValue, endValue, function, functionDiff, maxFehler):
    alpha = calcAlpha(startValue, endValue, functionDiff)
    print("alpha", alpha)
    x = [x0]
    n = 0
    while(True):
        time.sleep(1)
        n = n + 1
        x.append(function(x[n-1]))
        print("n:", n, "x:", x[n])
        fehlerabschatzung = abs(x[n] - x[n - 1]) # math.pow(alpha, n) / (1 - alpha)) *
        print("fehlerabschatzung", fehlerabschatzung)
        if(fehlerabschatzung < maxFehler):
            print("n: ", n)
            return x[n]


if __name__ == '__main__':
    result = iteration(x0=-0.1, startValue=-1, endValue=0, function=F, functionDiff=FDiff, maxFehler=math.pow(10, -6))
    #result = iteration(x0=-1, startValue=0, endValue=1, function=F, functionDiff=FDiff, maxFehler=math.pow(10, -6))
    print(result)