New Version 5.0!

Try it for free with our fully functional 60-day trial version.

Download now!

QuickStart Samples

Optimization In One Dimension QuickStart Sample (C#)

Illustrates the use of the Brent and Golden Section optimizer classes in the Extreme.Mathematics.Optimization namespace for one-dimensional optimization in C#.

Visual Basic code F# code IronPython code Back to QuickStart Samples

using System;

namespace Extreme.Mathematics.QuickStart.CSharp
{
	// The optimization classes resides in the 
	// Extreme.Mathematics.EquationSolvers namespace.
	using Extreme.Mathematics.Optimization;
	// Function delegates reside in the Extreme.Mathematics
	// namespace.
	using Extreme.Mathematics;

	/// <summary>
	/// Illustrates the use of the Brent and Golden Section optimizers
	/// in the Extreme.Mathematics.Optimization namespace of the
	/// Extreme Optimization Mathematics Library for .NET.
	/// </summary>
	class OptimizationIn1D
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			// Several algorithms exist for optimizing functions
			// in one variable. The most common one is
			// Brent's algorithm.

			// The function we are trying to minimize is called the
			// objective function and must be provided as a Func<double, double>. 
			// For more information about this delegate, see the
			// FunctionDelegates QuickStart sample.
			Func<double, double> f1 = new Func<double, double>(TestFunction1);
			Func<double, double> f2 = new Func<double, double>(TestFunction2);

			//
			// Brent's algorithm
			//

			// Now let's create the BrentOptimizer object.
			BrentOptimizer optimizer = new BrentOptimizer();
			
			// Set the objective function:
			optimizer.ObjectiveFunction = f1;
#if NET35
            // Of course, in C# 3.0, you can use lambda expressions:
            optimizer.ObjectiveFunction = x => x * x * x - 2 * x - 5;
#endif
			// Optimizers can find either a minimum or a maximum.
			// Which of the two is specified by the ExtremumType
			// property
			optimizer.ExtremumType = ExtremumType.Minimum;

			// The first phase is to find an interval that contains
			// a local minimum. This is done by the FindBracket method.
			optimizer.FindBracket(0, 3);
			// You can verify that an interval was found from the
			// IsBracketValid property:
			if (!optimizer.IsBracketValid)
				throw new Exception("An interval containing a minimum was not found.");

			// Finally, we can run the optimizer by calling the FindExtremum method:
			optimizer.FindExtremum();

			Console.WriteLine("Function 1: x^3 - 2x - 5");
			// The Status property indicates
			// the result of running the algorithm.
			Console.WriteLine("  Status: {0}", optimizer.Status);
			// The result is available through the
			// Result property.
			Console.WriteLine("  Minimum: {0}", optimizer.Result);
			double exactResult = Math.Sqrt(2/3.0);
			double result = optimizer.Extremum;
			Console.WriteLine("  Exact minimum: {0}", exactResult);

			// You can find out the estimated error of the result
			// through the EstimatedError property:
			Console.WriteLine("  Estimated error: {0}", optimizer.EstimatedError);
			Console.WriteLine("  Actual error: {0}", Math.Abs(result - exactResult));
			Console.WriteLine("  # iterations: {0}", optimizer.IterationsNeeded);

			Console.WriteLine("Function 2: 1/Exp(x*x - 0.7*x +0.2)");
			// You can also perform these calculations more directly 
			// using the FindMinimum or FindMaximum methods. This implicitly
			// calls the FindBracket method.
			result = optimizer.FindMaximum(f2, 0);
			Console.WriteLine("  Maximum: {0}", result);
			Console.WriteLine("  Actual maximum: {0}", 0.35);
			Console.WriteLine("  Estimated error: {0}", optimizer.EstimatedError);
			Console.WriteLine("  Actual error: {0}", result - 0.35);
			Console.WriteLine("  # iterations: {0}", optimizer.IterationsNeeded);

			//
			// Golden section search
			//

			// A slower but simpler algorithm for finding an extremum
			// is the golden section search. It is implemented by the
			// GoldenSectionMinimizer class:
			GoldenSectionOptimizer optimizer2 = new GoldenSectionOptimizer();

			Console.WriteLine("Using Golden Section optimizer:");
			result = optimizer2.FindMaximum(f2, 0);
			Console.WriteLine("  Maximum: {0}", result);
			Console.WriteLine("  Actual maximum: {0}", 0.35);
			Console.WriteLine("  Estimated error: {0}", optimizer2.EstimatedError);
			Console.WriteLine("  Actual error: {0}", result - 0.35);
			Console.WriteLine("  # iterations: {0}", optimizer2.IterationsNeeded);

			Console.Write("Press Enter key to exit...");
			Console.ReadLine();
		}

		// Minimum at x = Sqrt(2/3) = 0.816496580927726
		static double TestFunction1(double x)
		{
			return x*x*x - 2*x - 5;
		}

		// Maximum at x = 0.35
		static double TestFunction2(double x)
		{
			return 1/Math.Exp(x*x - 0.7*x +0.2);
		}
	}
}