121H-MATLAB代写
时间:2023-11-22
26/10/2023, 15:48solving_nonlinear_equations.ipynb - Colaboratory
Page 1 of 4https://colab.research.google.com/drive/1VwGyO1Ig84mg2hLlc4PBLidiWbqo121H
from matplotlib import pyplot as plt
Convergence of Newton's method
%matplo lib inline
import numpy as np
from matplotlib import pyplot as plt
# Test function
def fun(x):
  return x + np.exp(-20 * x * x) * np.cos(x)
def deriv(x):
  return 1 - np.exp(-20 * x * x) * np.sin(x) - 40 * x * np.exp(-20 * x * x) * np.cos(x)
# Plot the function
xx = np.linspace(-1, 1, 1000)
yy = fun(xx)
dyy = deriv(xx)
fig, (ax1, ax2) = plt.subplots(2)
fig.tight_layout(pad=2.0)
ax1.plot(xx, yy)
ax1.set_title('f(x)')
ax2.plot(xx, dyy)
ax2.set_title('df(x)');
26/10/2023, 15:48solving_nonlinear_equations.ipynb - Colaboratory
Page 2 of 4https://colab.research.google.com/drive/1VwGyO1Ig84mg2hLlc4PBLidiWbqo121H

# Newton's method
def newton(fun, deriv, x0, tol=1E-5, niter=10):
  """Solve a nonlinear equation via Newton's method."""
  errors = []
  xvalues = []
  x = x0
  for _ in range(niter):
    dt = -fun(x) / deriv(x)
    errors.append(np.abs(dt))
    x = x + dt
    xvalues.append(x)
    if np.abs(dt) < tol:
      break
  return x, xvalues, errors
# Test of Newton's method
26/10/2023, 15:48solving_nonlinear_equations.ipynb - Colaboratory
Page 3 of 4https://colab.research.google.com/drive/1VwGyO1Ig84mg2hLlc4PBLidiWbqo121H
Errors:
1.0
0.999999952606113
0.9999980094605663
0.999998009456923
0.9999980093075479
0.9999980093075475
0.9999980093075292
0.9999980093075292
0.9999980093075292
0.9999980093075292
alpha:
-1.0
-4.739388703711711e-08
-0.9999980568544533
-4.739753034499472e-08
-0.9999980567050782
-4.739753078908393e-08
-0.99999805670506
-4.739753078908393e-08
-0.99999805670506
-4.739753078908393e-08
alpha, alpha_values, errors = newton(fun, deriv, 0, tol=1E-14)
print("Errors:")
for err in errors:
  print(err)
print("")
print("alpha:")
for a in alpha_values:
  print(a)
26/10/2023, 15:48solving_nonlinear_equations.ipynb - Colaboratory
Page 4 of 4https://colab.research.google.com/drive/1VwGyO1Ig84mg2hLlc4PBLidiWbqo121H
essay、essay代写