Advertisement
slik1977

GoldenSection

Mar 17th, 2022
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.05 KB | None | 0 0
  1. using System;
  2.  
  3. public class GoldenSectionMethod
  4. {
  5.     public static readonly double Phi = (1 + Math.Sqrt(5)) / 2;
  6.     public readonly double Accuracy;
  7.  
  8.     public readonly Func<double, double> Func;
  9.  
  10.     public GoldenSectionMethod(Func<double, double> func, double accuracy = 0.01)
  11.     {
  12.         if (func is null)
  13.             throw new Exception("Function is null");
  14.  
  15.         if (accuracy <= 0)
  16.             throw new Exception("Wrong accuracy");
  17.  
  18.         Func = func;
  19.         Accuracy = accuracy;
  20.     }
  21.  
  22.     public double FindMin(double start, double end)
  23.     {
  24.         int counter = 0;
  25.         while (Math.Abs(end - start) >= Accuracy)
  26.         {
  27.             var x1 = end - (end - start) / Phi;
  28.             var x2 = start + (end - start) / Phi;
  29.  
  30.             if (Func(x1) >= Func(x2))
  31.                 start = x1;
  32.             else
  33.                 end = x2;
  34.             counter++;
  35.         }
  36.  
  37.         Console.WriteLine($"Number of iterations for the First Part of GoldenSection method {counter} ");
  38.         return (start + end) / 2;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement