0
votes

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 graph looks like this enter image description here

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

Wolfram Alpha

2

2 Answers

0
votes

(1) You don't.

In general (or by default), we assume that the search space is on the real Cartesian plane. Your function and derivative are undefined for x < 0. Thus, you need to either take a smaller step in that direction, or search for a value of x within your process's radius of convergence.

(2) You already do.

Another possibility is to continue as you have, searching 4D complex space. The answer you reached is quite reasonable in that space. Look at your answer: the real component is just what you'd want, and the imaginary component is quite close to zero.

If you require a real-only answer with demonstrated convergence, then take that real component and feed it back into your algorithm as the initial guess. You'll converge on a proven result within two iterations.

0
votes

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))