Advertisement
V4L304

Untitled

Dec 18th, 2021
1,337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. using System.Diagnostics;
  2. using YuKu.MathExpression;
  3.  
  4. public class BisectionClass
  5. {
  6.     private static double Func(string expression, double x)
  7.     {
  8.         Func<double, double> func = expression.AddModule(typeof(Math)).AddParameter("x").Compile<Func<double, double>>();
  9.         double res = func(x);
  10.         return res;
  11.     }
  12.  
  13.     public static void Bisection(string expression,
  14.                           double a,
  15.                           double b)
  16.     {
  17.         double c = a;
  18.         Stopwatch stopWatch = new();
  19.         stopWatch.Start();
  20.         double count = 0;
  21.         if (b < a)
  22.         {
  23.             double tmp = a;
  24.             a = b;
  25.             b = tmp;
  26.         }
  27.         while ((b - a) >= 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)
  28.         {
  29.             c = (a + b) / 2;
  30.             if (Func(expression, c) == 0.0)
  31.                 break;
  32.             else if (Func(expression, c) * Func(expression, a) < 0)
  33.                 b = c;
  34.             else
  35.                 a = c;
  36.  
  37.             count++;
  38.         }
  39.         Console.WriteLine(count);
  40.         stopWatch.Stop();
  41.         TimeSpan ts = stopWatch.Elapsed;
  42.         string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
  43.             ts.Hours, ts.Minutes, ts.Seconds,
  44.             ts.Milliseconds / 10);
  45.         Console.WriteLine($"la radice equivale a {Math.Round(c, 15)} in {elapsedTime}");
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement