Advertisement
daniv1

bisection

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