|
| 1 | +""" |
| 2 | +Created on Mon Jan 30 12:53:04 2023 |
| 3 | +
|
| 4 | +@author: utkucaylan |
| 5 | +
|
| 6 | +============================================================================================= |
| 7 | +Numberical Methods |
| 8 | + --> Roots of Equations (i. Bracketing ii. Open iii. Roots of Polynomials) |
| 9 | + --> Open Methods: Only a single starting value of x is required |
| 10 | + i. Simple Fixed-Point Iteration |
| 11 | + ii. Newton Rapson Method |
| 12 | + iii. Secant Method |
| 13 | + iv. Brent`s Method |
| 14 | + v. Multiple Roots |
| 15 | + vi. Systems of Nonlinear Equations |
| 16 | + |
| 17 | + --> Secant Method |
| 18 | + |
| 19 | +A potential problem in implementing the Newton-Raphson method is the evaluation of the |
| 20 | +derivative. Although this is not inconvenient for polynomials and many other functions, |
| 21 | +there are certain functions whose derivatives may be extremely difficult or inconvenient to |
| 22 | +evaluate. For these cases, the derivative can be approximated by a backward finite divided |
| 23 | +difference. |
| 24 | +
|
| 25 | +P.S. See the figures for more details. |
| 26 | +============================================================================================= |
| 27 | +""" |
| 28 | + |
| 29 | +""" |
| 30 | +
|
| 31 | +Problem: Use secant method to locate the root of f(x) = e^{−x} − x. Start |
| 32 | +with initial estimates of x_{-1} = 0 and x_{0} = 1 |
| 33 | +
|
| 34 | +""" |
| 35 | +import math |
| 36 | +import numpy as np |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +x_i = 0 |
| 41 | +x_ii = 1 |
| 42 | +counter = 0 |
| 43 | +while counter < 100: |
| 44 | + counter = counter + 1 |
| 45 | + #function value at x_i |
| 46 | + f_i = math.exp(-x_i) - x_i |
| 47 | + #function value at x_ii |
| 48 | + f_ii = math.exp(-x_ii) - x_ii |
| 49 | + |
| 50 | + # compute the new root at x_iii |
| 51 | + x_iii = x_ii - (f_ii*(x_i-x_ii))/(f_i-f_ii) |
| 52 | + |
| 53 | + # percentage error |
| 54 | + delta_x = np.abs((x_iii - x_ii)/x_ii*100) |
| 55 | + x_i = x_ii |
| 56 | + x_ii = x_iii |
| 57 | + |
| 58 | + print("The percentage error %.8f" % delta_x) |
| 59 | + if delta_x < 1e-6: |
| 60 | + print("The total number of iterations is %.0f" % counter) |
| 61 | + print("The root of the given function is %.4f" % x_iii) |
| 62 | + break |
| 63 | + |
0 commit comments