Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- public class DichotomyMethod
- {
- public readonly double Accuracy;
- public readonly double Step;
- public DichotomyMethod(double accuracy = 0.01, double step = 0.001)
- {
- if (accuracy <= 0)
- throw new Exception("Wrong accuracy");
- if (step <= 0)
- throw new Exception("Wrong step");
- Accuracy = accuracy;
- Step = step;
- }
- public (double, double) FindRoot(Func<double, double> func, double start, double end)
- {
- if (start > end)
- throw new Exception("Wrong interval");
- if (2 * Step >= Accuracy)
- throw new Exception("Wrong step && accuracy");
- var len = 1d;
- int counter = 0;
- double initialStart = start, initialEnd = end;
- for (var i = 1; len > Accuracy; ++i)
- {
- var x1 = (start + end) / 2 - Step;
- var x2 = (start + end) / 2 + Step;
- if (func(x1) < func(x2))
- {
- end = x2;
- }
- else
- {
- start = x1;
- }
- len = (initialEnd - initialStart - 2 * Step) / Math.Pow(2, i - 1) + 2 * Step;
- counter++;
- }
- Console.WriteLine($"Number of iterations for the DichotomyMethod {counter} ");
- return (start, end);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement