Advertisement
mmayoub

grad solution

May 24th, 2023
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | Source Code | 0 0
  1. class Gradiant:
  2.     M = 3
  3.    
  4.     @staticmethod
  5.     def g(i, x):
  6.         if i == 0:
  7.             return x * x - 5 * x + 4
  8.         elif i == 1:
  9.             return x * x - 3 * x
  10.         else:
  11.             return x * x - 2 * x
  12.    
  13.     @staticmethod
  14.     def grad(i, x):
  15.         if i == 0:
  16.             return 2 * x - 5
  17.         elif i == 1:
  18.             return 2 * x - 3
  19.         else:
  20.             return 2 * x - 2
  21.    
  22.     @staticmethod
  23.     def nextX(i, x):
  24.         g_val = Gradiant.g(i, x)
  25.         if g_val <= 0:
  26.             return x
  27.         grd = Gradiant.grad(i, x)
  28.         return x - (g_val / grd)
  29.    
  30.     @staticmethod
  31.     def findZero(i, x):
  32.         print()
  33.         print(f"start finding zero point for g{i+1} from x={x}")
  34.         while Gradiant.g(i, x) > 0:
  35.             print(f"g{i+1}({x}) = {Gradiant.g(i, x)}")
  36.             x = Gradiant.nextX(i, x)
  37.         print(f"zero point found for g{i+1} at x={x}")
  38.         return x
  39.    
  40.     @staticmethod
  41.     def findRangEdge(x):
  42.         for i in range(Gradiant.M):
  43.             x = Gradiant.findZero(i, x)
  44.         print(f"range edge found at x = {x}")
  45.         return x
  46.    
  47. low = Gradiant.findRangEdge(-5)
  48. print(f"Range low = {low}")
  49. high = Gradiant.findRangEdge(low + 2)
  50. print(f"Range high = {high}")
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement