Search This Blog

Monday 10 August 2015

Create a Regular Falsi Method Scheme in C#


REGULAR FALSI METHOD




using System;

namespace RegularFalsiMethod
{
    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++)
                    { Console.Write("Value 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 btw intervals");
                        while (true)
                        {//midpoint of line
                            x0 = ((x1 * y2) - (x2 * y1)) / (y2 - y1);
                            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("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 btw 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");
        }
}

}


Happy CODING!!!

No comments:

Post a Comment