Implementation of Secant Method written in C#.
IN -3 -1 0.0000001 OUT X: -3 f(x): 2 X: -2 f(x): -1 X: -3 f(x): 2 X: -2.33333333333333 f(x): -0.222222222222222 X: -2.4 f(x): -0.0400000000000003 X: -2.41463414634146 f(x): 0.00118976799524062 X: -2.41421143847487 f(x): -6.00728683874951E-06
using System; // ? 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net namespace Secant_Method_CS { class Program { static void Main(string[] args) { double xn1; //x_(n - 1) double xn; //x_(n) double x; double precision; Console.Write("Enter beginning of interval: "); xn1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter end of interval: "); xn = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter precision of method: "); precision = Convert.ToDouble(Console.ReadLine()); if (Function(xn1) * Function(xn) > 0.0D) { Console.Write("Function has same signs at ends of interval"); return; } x = xn1; while (Math.Abs(Function(x)) > precision) { Console.WriteLine("X: " + x + " f(x): " + Function(x)); x = xn - ((Function(xn) * (xn - xn1)) / (Function(xn) - Function(xn1))); xn1 = xn; xn = x; } Console.ReadKey(); //Wait } static double Function(double x) //x^2 + 2x -1 { return x * (x + 2) - 1; } } }
C# Secant Method