I am trying to solve to the equation
f(x) = cos(x) - sqrt(x)
using Newton-Raphson Method in python
f'(x) = -sin(x) - (1/2*sqrt(x))
For my starting guess, I'm trying values form 0 to 4. It works fine from the range 0.00001 to 2.45
The problem is that beyond 2.45, It enters imaginary(complex numbers). How do I handle generating complex number with this?
import numpy as np
def eqn(x):
return np.cos(x) - np.sqrt(x)
def eqn_derivation(x):
return (-(1/(2*(np.sqrt(x)))) - (np.sin(x)))
def new-raphson(eqn,eqn_derivation,start_guess,eps):
x0=start_guess
if funDeriv(x0) != 0:
x1=x0-fun(x0)/funDeriv(x0)
while np.abs(x1-x0)>eps:
x0=x1
if funDeriv(x0) != 0:
x1=x0-fun(x0)/funDeriv(x0)
return x1
Wolfram Alpha suggests that 2nd iteration spits out complex numbers. I'm not sure how to return/generate/convert/handle function values returning complex numbers
I was able to solve the answer using the CMATH Library
import numpy as np
def eqn(x):
return cmath.cos(x) - cmath.sqrt(x)
def eqn_derivation(x):
return (-(1/(2*(cmath.sqrt(x)))) - (cmath.sin(x)))
def new-raphson(eqn,eqn_derivation,start_guess,eps):
x0=start_guess
if funDeriv(x0) != 0:
x1=x0-fun(x0)/funDeriv(x0)
while np.abs(x1-x0)>eps:
x0=x1
if funDeriv(x0) != 0:
x1=x0-fun(x0)/funDeriv(x0)
return x1
Output -
(0.6417, (0.6417-5.61e-28j))