Search This Blog

Monday 10 August 2015

How to create a Bisection Method Scheme of any power in C#

 
BISECTION METHOD USING C#


Here's the Code
using System;
namespace BisectionMethod
{
    class Program
    {
        static void Main(string[] args)
        {  string retry = "";
            do{ try
                {  float y1 = 0, y2 = 0;
                    //collect inputs
                    Console.Write("\n1st Interval: ");
                    float x1 = float.Parse(Console.ReadLine());
                    Console.Write("2nd Interval: ");
                    float x2 = float.Parse(Console.ReadLine());
                    float x0 = 0, y0 = 0;
                    Console.Write("Highest power in equation: ");
                    int pwr = int.Parse(Console.ReadLine());
                    //store in an array
                    int[] coe = new int[pwr + 1];
                    //calculate values of y1 and y2 using for loop
                for (int i = 0; i < coe.Length; i++)
             { if (i == 0) { Console.Write("Value of constant: "); }
          else{Console.Write("Coefficient of variable with power {0}: ", i);}
                        coe[i] = int.Parse(Console.ReadLine());
                        y1 += (float)(coe[i] * Math.Pow(x1, i));
                        y2 += (float)(coe[i] * Math.Pow(x2, i));
                    } //determine negative
                    if ((y1 * y2) < 0)
                    {Console.WriteLine("There is a root between intervals");
                        while (true)
                        {//midpoint (x0)
                            x0 = (x1 + x2) / 2;
                            for (int i = 0; i < coe.Length; i++)
                            { y0 += (float)(coe[i] * Math.Pow(x0, i)); }
                            if (y0 * y1 < 0)//check for -ve product
                            { x2 = x0; }
                            else{ x1 = x0;}
                            //approximate y to 6 decimal places
                            y0 = (float)Math.Round(y0, 6);
                            //if y0=0 therefore root is x0
       if (y0 == 0) { Console.WriteLine("\n The Root is {0}", x0); break; }
                           y0 = 0;
//reset y0 back to zero in order to avoid accumulation of result
                } }
               else{ Console.WriteLine("There is NO root between intervals"); }
                }

                catch { Console.WriteLine("\a\a\a Error \nInvalid Input"); }
      Console.Write("\nDo you wish to try again, type \"Yes\" or otherwise to quit: ");
     retry = Console.ReadLine().ToUpper();
            } while (retry == "YES");
}
}


}
VIDEO ON YOUTUBE



Happy Programming!!!

2 comments: