Advertisement
slik1977

dichotomy

Mar 17th, 2022
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. using System;
  2.  
  3. public class DichotomyMethod
  4. {
  5.     public readonly double Accuracy;
  6.     public readonly double Step;
  7.  
  8.     public DichotomyMethod(double accuracy = 0.01, double step = 0.001)
  9.     {
  10.         if (accuracy <= 0)
  11.             throw new Exception("Wrong accuracy");
  12.  
  13.         if (step <= 0)
  14.             throw new Exception("Wrong step");
  15.  
  16.         Accuracy = accuracy;
  17.         Step = step;
  18.     }
  19.  
  20.     public (double, double) FindRoot(Func<double, double> func, double start, double end)
  21.     {
  22.         if (start > end)
  23.             throw new Exception("Wrong interval");
  24.         if (2 * Step >= Accuracy)
  25.             throw new Exception("Wrong step && accuracy");
  26.  
  27.         var len = 1d;
  28.         int counter = 0;
  29.         double initialStart = start, initialEnd = end;
  30.         for (var i = 1; len > Accuracy; ++i)
  31.         {
  32.             var x1 = (start + end) / 2 - Step;
  33.             var x2 = (start + end) / 2 + Step;
  34.  
  35.             if (func(x1) < func(x2))
  36.             {
  37.                 end = x2;
  38.             }
  39.             else
  40.             {
  41.                 start = x1;
  42.             }
  43.  
  44.             len = (initialEnd - initialStart - 2 * Step) / Math.Pow(2, i - 1) + 2 * Step;
  45.             counter++;
  46.         }
  47.  
  48.         Console.WriteLine($"Number of iterations for the DichotomyMethod {counter} ");
  49.         return (start, end);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement