Figure 1.3:

An iteration of the Newton-Raphson method for solving f(x)=0 in the scalar case.

Code for Figure 1.3

Text of the GNU GPL.

main.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import numpy as np
import matplotlib.pyplot as plt

npts = 20
xlow = 2
xhigh = 3.75
x = np.linspace(xlow, xhigh, npts)

def f(x):
    return x**3 - 2*x**2 + 3*x - 6

def df(x):
    return 3*x**2 - 4*x + 3

fx = f(x)

x0 = 3
fx0 = f(x0)
dfx0 = df(x0)

x1 = x0 - fx0/dfx0
fx1 = f(x1)

gap = 0.75
xzero = np.array([xlow, xhigh])
xzero.shape = (2,1)
yzero = np.array([0, 0])
yzero.shape = (2,1)
xt0 = np.array([x1, x0 + gap])
xt0.shape = (2,1)
yt0 = fx0 + dfx0 * (xt0 - x0)
yt0.shape = (2,1)

axispts = np.array([[x0, 0, x1, 0],
                    [x0, fx0, x1, fx1],
                    [xlow, fx0, xlow, fx1]])

tangents = np.column_stack ((xzero, yzero, xt0, yt0))

plt.figure()
plt.plot(x, fx, 'b')
plt.plot(axispts[:,0], axispts[:,1])
plt.plot(axispts[:,2], axispts[:,3])
plt.plot(xzero, yzero, 'g')
plt.plot(xt0, yt0, 'y')
plt.show(block=False)

# Correct data export section
with open("newton.dat", "w") as f:
    np.savetxt(f, np.column_stack((x, fx)), fmt='%f', header="Table x and f(x)")
    f.write("\n\n")
    np.savetxt(f, axispts, fmt='%f', header="Axes Points")
    f.write("\n\n")
    np.savetxt(f, tangents, fmt='%f', header="Tangents")
    f.write("\n\n")
    np.savetxt(f, np.array([x0, fx0, x1, fx1]).reshape(1, -1), fmt='%f', header="Curve Points")