Search code examples
pythonpython-3.xlogarithmderivativenewtons-method

Why is this newton-rapshon method of finding the returning an error with log


As stated above I've made a newton-raphson method for finding the square root of a given number

def newton(f, fprime, eps):

    x0 = 10
    while True:
        fx0 = f(x0)
        if abs(fx0) < eps:
            return x0
        fpx0 = fprime(x0)
        if fpx0 == 0:
            return None
        x0 = x0 - fx0/fpx0

I know that generally you shouldn't use a while True loop but in my case it is fine, my problem is when f(x)=logx and f'(x) = 1/x, I run the code and get a math error, I'm assuming either from logging a negative or dividing by 0. Either way some help on how to fix it would be great, as i just can't seem to find why only log is having the issue


Solution

  • Try changing your initial x0 guess to a value closer to the root.

    x0 = 2 will give you the solution, for example.