def sqrt(n):
ret = n
while ret * ret > n:
ret = (ret + n / ret) / 2
return ret

print(sqrt(4))
print(sqrt(2))

2.0
1.414213562373095


from matplotlib import pyplot as plt
import numpy as np
%matplotlib notebook

xs = np.linspace(-6, 6, 1000)
ys = [x * x - 4 for x in xs]

plt.xlabel('x')
plt.ylabel('y')
plt.plot(xs, [0] * 1000)
plt.plot([0] * 1000, np.linspace(-6, 30, 1000))
plt.plot(xs, ys)

<IPython.core.display.Javascript object>

[<matplotlib.lines.Line2D at 0x1217b25f8>]


def f(x):
return x * x - 4

xs = np.linspace(-6, 6, 1000)
ys = [f(x) for x in xs]

plt.xlabel('x')
plt.ylabel('y')
plt.plot(xs, [0] * 1000)
plt.plot([0] * 1000, np.linspace(-6, 30, 1000))
plt.plot(xs, ys)
plt.plot(4, f(4), 'ro')
plt.annotate('x0(4, 12)', (2, 12))
plt.plot([4, 4], [0, 12], '--')

k0 = (f(4 + 0.1) - f(4 - 0.1)) / 0.2
b0 = f(4) - k0 * 4

def f_tangent0(x):
"""
点x0的切线方程
"""
return k0 * x + b0

xs = np.linspace(2, 6, 1000)
ys = [f_tangent0(x) for x in xs]
plt.plot(xs, ys)

plt.plot(2.5, f(2.5), 'ro')
plt.annotate('x1(2.5, 2.25)', (0.5, 5))
plt.plot([2.5, 2.5], [0, 2.25], '--')

k1 = (f(2.5 + 0.1) - f(2.5 - 0.1)) / 0.2
b1 = f(2.5) - k1 * 2.5

def f_tangent1(x):
"""
点x1的切线方程
"""
return k1 * x + b1

xs = np.linspace(1, 6, 1000)
ys = [f_tangent1(x) for x in xs]
plt.plot(xs, ys)

# plt.plot(2.05, f(2.05), 'ro')
# plt.annotate('x1(2.05, 0.2)', (2.05, -5))

<IPython.core.display.Javascript object>

[<matplotlib.lines.Line2D at 0x12ee97c18>]


def sqrt(n):
ret = n
while ret * ret > n:
ret = (ret + n / ret) / 2
return ret