Consider the equation $f(x) = 0$, which $f(x)$ is one-time differentiable. Given a reasonable starting point $x_0$, we may approximate the solution of $f(x) = 0$ by linearizing $f(x)$:
$$f(x) \sim f(x_0) + f'(x_0)(x-x_0)$$
If $f(x) = 0$ then
$$f(x_0) + f'(x_0)(x-x_0) \sim 0 \Rightarrow x \sim x_0 - \frac{f(x_0)}{f'(x_0)}$$
Thus we may apply this iteratively to obtain a better solution. i.e. set
$$x_{n+1} \sim x_n - \frac{f(x_n)}{f'(x_n)},  n \geq 0$$

## Preparation


```python
%matplotlib inline
%pylab
```

    Using matplotlib backend: Qt5Agg
    Populating the interactive namespace from numpy and matplotlib



```python
import sympy as sp
x = sp.symbols('x')
f = sp.Function('f')
Df = sp.Function('Df')
```

## Code


```python
def newton_raphson(f, x0, max_iteration, tolerance):
    
    # Initialization
    y = x0
    ylist = [y]
    Df = sp.diff(f,x)
    
    # Loop
    for n in range(max_iteration):
        ynew = y - f.evalf(subs={x: y})/Df.evalf(subs={x: y})
        ylist.append(ynew)
        if abs(ynew-y) < tolerance:
            break
        else:
            y = ynew
    
    actual_iteration=len(ylist)-1
    print(actual_iteration)
    
    return ylist
```

## Testing Cell


```python
# For obtaining estimates
f = x**3-2*x-5
yran = newton_raphson(f, 2.5, 30, 10**(-16))
print(yran)
```

    6
    [2.5, 2.16417910447761, 2.09713535581055, 2.09455523239045, 2.09455148155025, 2.09455148154233, 2.09455148154233]



```python
# For seeing accuracy
estzero = [f.evalf(subs={x: i}) for i in yran]
plot(estzero)
```

c17bd08585638b1bb0ad21adcbb93dea45da35ca
ipynb
Jupyter Notebook
M1C (Python)/M1C-Numerical Solutions to Equations I/Newton Method.ipynb
ImperialCollegeLondon/Random-Stuff
219bc0e26ea6f5ee7548009c849959b268f54821
MIT
2021-05-16T04:08:34.000Z
2021-11-27T12:56:10.000Z
M1C (Python)/M1C-Numerical Solutions to Equations I/Newton Method.ipynb
ImperialCollegeLondon/Random-Stuff
219bc0e26ea6f5ee7548009c849959b268f54821
MIT
M1C (Python)/M1C-Numerical Solutions to Equations I/Newton Method.ipynb
ImperialCollegeLondon/Random-Stuff
219bc0e26ea6f5ee7548009c849959b268f54821
MIT
2020-03-31T00:23:13.000Z
2020-05-13T15:01:46.000Z
Qwen/Qwen-72B
1. YES
2. YES