import numpy as np

def f(x):
    return eval(funzione)

def derivata(pt):
    h=0.00001
    return (f(pt+h)-f(pt))/h

def zeri(a, b):
    if f(a)*f(b)>=0:
        print("Intervallo non valido")
        return False
    return True

def Newton(x0, tolleranza):
    qt=0

    while True:
        x1=x0-f(x0)/derivata(x0)
        qt+=1

        if abs(x1-x0)<=tolleranza:
            return x1, qt

        x0=x1

def bisezione(a, b, tolleranza):
    if zeri(a, b)==False:
        return None

    if a>b:
        k=a
        a=b
        b=k

    qt=0

    while True:
        c=(a+b)/2
        qt+=1 

        if f(c)==0 or (b-a)/2<=tolleranza:
            return c, qt

        if f(a)*f(c)<0:
            b=c
        else:
            a=c

funzione="np.e**(-x)-x"
tolleranza=0.000001

zero, n=Newton(0, tolleranza)
print("Newton:", zero, "\tIterazioni:", n)

zero, n=bisezione(0, 1, tolleranza)
print("\nBisezione:", zero, "\tIterazioni:", n)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: