Advertisement
daniv1

bisection 2.0

Feb 20th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Bisection
  4. {
  5.     class Bisection
  6.     {
  7.         public static void Swap<T>(ref T a, ref T b)
  8.         {
  9.             T c = a;
  10.             a = b;
  11.             b = c;
  12.         }
  13.  
  14.  
  15.         static double func(double x)
  16.         {
  17.             return x*x - 4;
  18.         }
  19.  
  20.         public static void bisection(double a, double b,double EPSILON)
  21.         {
  22.             int cnt = 0;
  23.             if (func(a) * func(b) >= 0)
  24.             {
  25.                 Console.WriteLine("You have not assumed right a and b");
  26.                 return;
  27.             }
  28.             else if(Math.Abs(func(a)) <= EPSILON)
  29.             {
  30.                 Console.WriteLine("x = " + a + " ; cnt = "+ cnt);
  31.                 return;
  32.             }
  33.             else if(Math.Abs(func(b))<=EPSILON)
  34.             {
  35.                 Console.WriteLine("x = " + b + " ; cnt = " + cnt);
  36.                 return;
  37.             }
  38.             double c = a;
  39.             while ((b - a) >= EPSILON)
  40.             {
  41.                 cnt++;
  42.                 c = (a + b) / 2;
  43.  
  44.                 if (func(c) == 0.0)
  45.                     break;
  46.  
  47.                 else if (func(c) * func(a) < 0)
  48.                     b = c;
  49.                 else
  50.                     a = c;
  51.             }
  52.  
  53.             Console.WriteLine("The value of " +
  54.                               "root is : " + c + " ;cnt = " + cnt);
  55.  
  56.         }
  57.     }
  58.     class Program
  59.     {
  60.         static void Main(string[] args)
  61.         {
  62.             Console.WriteLine("Input a");
  63.             double a = Convert.ToDouble(Console.ReadLine());
  64.             Console.WriteLine("Input b");
  65.             double b = Convert.ToDouble(Console.ReadLine());
  66.             Console.WriteLine("Input epsilon");
  67.             double epsilon = Convert.ToDouble(Console.ReadLine());
  68.             if(a>b)
  69.             {
  70.                 Bisection.Swap(ref a, ref b);
  71.             }
  72.             Bisection.bisection(a, b, epsilon);
  73.             Console.ReadLine();
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement