Math in C# using the Quadratic Formula

Microsoft .NET
namespace QuadraticFunc 
{
    using System;
    using System.Diagnostics;

    class Program 
    {
        static void Main(string[] args) 
        {
            Action<object> Print = (obj) => { Debug.WriteLine(obj.ToString()); };

            // Returns Quadratic (+,-)
            Func<double, double, double, Tuple<double, double>> Quadratic = (a, b, c) => {
                double x1 = (-b + Math.Sqrt((b * b) - ((4 * a) * c))) / (2 * a);
                double x2 = (-b - Math.Sqrt((b * b) - ((4 * a) * c))) / (2 * a);
                return new Tuple<double, double>(x1, x2);
            };

            Print(Quadratic(1, 3, -4));     // (1, -4)
            Print(Quadratic(2, -4, -3));    // (2.58113883008419, -0.58113883008419)
            Print(Quadratic(0, 0, 0));      // (NaN, NaN)

            Tuple<double, double> result = Quadratic(1, 3, -4);
            Print(result.Item1);
            Print(result.Item2);
        }
    }
}

Simple enough. If you want to ensure exact order translate the local variable function Func(Of double,double,double,Tuple(Of double,double)) to an actual member function or static function.

Leave a Comment