0

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

Ktass99
  • 73
  • 9
  • In the title you reference computing a square root, in the body you talk about a logarithm... could you please decide what are you asking for? Further, the indentation of the function body is not correct. For those reasons, please [edit] your question. – gboffi May 23 '20 at 21:42
  • I had the square root as an explanation of the newton method, I see that it is not useful as someone who could help would most likely already be familiar – Ktass99 May 23 '20 at 21:47

1 Answers1

1

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

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

Burnstrike
  • 71
  • 4
  • I had the value set to 4 before and it still did not work, do you have an explanation as to why changing that number works? curiosity obviously as now the function is good to go – Ktass99 May 23 '20 at 22:19
  • https://en.wikipedia.org/wiki/Newton%27s_method The section on 'practical considerations' is of use here and discusses some of the limitations of the N-R method. Your initial guess will need to be close enough to the solution to converge, this varies from function to function. If you encounter issues with the N-R, try a different root finding method such as bisection method, which is slower, but may work for a function that the N-R has trouble with. – Burnstrike May 23 '20 at 22:28