Facebook
From Soft Kangaroo, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 137
  1. import math
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. def func2 (x):
  5.     return((2*x**2)-5*x-12)
  6.  
  7. def false_position(fx, xl, xu, iter_num):
  8.     ea_xr = []
  9.     for i in range(iter_num):
  10.         xr = (xl*fx(xu) - xu*fx(xl)/(fx(u)- fx(xl))
  11.         ea_xr.append(xr)
  12.         if (fx(xl)*fx(xr) < 0):
  13.               xu=xr
  14.         else:
  15.               xl = xr
  16.         return ea_xr
  17. false_position(func2,0,7,20)
  18.              
  19. def bisect(fc, xl, xu, iternum):
  20.               estimates_xr = []
  21.               for i in range(iternum):
  22.               xr = (xl + xu)/2
  23.               estimates_xr.append(xr)
  24.               if (fx(xl)*fx(xr)
  25.                  xu = xr
  26.               else:
  27.                   xl = xr
  28.             return estimates_xr
  29.     bisect(func2, 0, 7, 20)
  30.                  
  31. def new_raph1(func, dfunc, xinit, ea, imax=20):
  32.                   iter=0
  33.                   xold=xinit
  34.                   roots=[]
  35.                   errors=[]
  36.                   while (iter < imax):
  37.                   xnew= xold- (func(xold)/dfunc(xold))
  38.                   roots.appends(xnew)
  39.                  
  40.                   err = (np.abs((xnew - xold)/xnew)) * 100
  41.                   xold = xnew
  42.                   errors.append(err)
  43.                   if (err<ea):
  44.                 iter += 1
  45.                   return roots,errors
  46.       x,y = new_raph(func2, der2, 0, 0)
  47.       print("roots = ", np.round(x,7), ,"\n", ,"errors = ", np.round(y,7))