mardi 27 octobre 2020

Implement Newton's method in python with a random number

The requirement is to use Newton's method to find the root of a function.

def newton(f, fprime, eps, maxiter=5000):
    from random import randint
    x = randint(-100, 100); n = 0
    # print(x)
    try:
        while n < maxiter:
            if abs(f(x)) < eps:
                # print(x)
                return x
            x = x - f(x)/fprime(x)
            # print(x)
            n += 1
            # print(n)
        return None
    except (ZeroDivisionError, ValueError):
        newton(f, fprime, eps, maxiter=5000)

The input function may not have a root, so maxiter is needed. Also needs to deal with the situation where f(x) doesn't exist or f'(x) = 0, so I chose to use random and call the function again.

When I test it with f = ln(x) and fprime = 1/x, it always returns nothing. The print functions in comments are just for test use, it seems that it can find the right value, just doesn't return it. I don't quite understand what's happening here.




Aucun commentaire:

Enregistrer un commentaire