Extreme Optimization > Mathematics Library for .NET > QuickStart Samples > NumericalDifferentiation QuickStart Sample (C#)

Extreme Optimization Mathematics Library for .NET

NumericalDifferentiation QuickStart Sample (C#)

Illustrates the use of the NumericalDifferentiator class (Extreme.Mathematics.Calculus namespace) for numerical differentiation in C#.

VB.NET code Back to QuickStart Samples

using System;

namespace Extreme.Mathematics.QuickStart.CSharp
{
    // The numerical differentiation classes reside in the
    // Extreme.Mathematics.Calculus namespace.
    using Extreme.Mathematics.Calculus;
    // Function delegates reside in the Extreme.Mathematics
    // namespace.
    using Extreme.Mathematics;

    /// <summary>
    /// Illustrates numerical differentiation using the
    /// NumericalDifferentiator class in the Extreme.Mathematics.Calculus 
    /// namespace of the Extreme Optimization Mathematics 
    /// Library for .NET.
    /// </summary>
    class NumericalDifferentiation
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Numerical differentiation is a fairly simple
            // procedure. Its accuracy is inherently limited
            // because of unavoidable round-off error.
            //
            // All calculations are performed by static methods
            // of the NumericalDifferentiator class.
            double result;
            double estimatedError;

            //
            // Standard numerical differentiation.
            //

            // Central differences are the standard way of
            // approximating the result of a function.
            // For this to work, it must be possible to 
            // evaluate the target function on both sides of
            // the point where the numerical result is
            // requested.
            //
            // The target function must be provided as a 
            // RealFunction. For more information about 
            // this delegate, see the FunctionDelegates 
            // QuickStart Sample.
            RealFunction fCentral =
                new RealFunction(Math.Cos);
            Console.WriteLine("Central differences:");
            // The actual calculation is performed by the
            // CentralDerivative method.
            result = NumericalDifferentiator.CentralDerivative(
                fCentral, 1);
            Console.WriteLine("  Result = {0}", result);
            Console.WriteLine("  Actual = {0}", -Math.Sin(1));
            // This method is overloaded. It has an optional
            // out parameter that returns an estimate for the
            // error in the result.
            result = NumericalDifferentiator.CentralDerivative(
                fCentral, 1, out estimatedError);
            Console.WriteLine("Estimated error = {0}", 
                estimatedError);

            //
            // Forward and backward differences.
            //

            // Some functions are not defined everywhere.
            // If the result is required on a boundary
            // of the domain where it is defined, the central
            // differences method breaks down. This also happens
            // if the function has a discontinuity close to the
            // differentiation point.
            // 
            // In these cases, either forward or backward 
            // differences may be used instead.
            //
            // The FForward function at the end of this file
            // is an example of a function that may require
            // forward differences. It is undefined for
            // x < -2.
            RealFunction fForward =
                new RealFunction(FForward);
            // Calculating the derivative using central 
            // differences returns NaN (Not a Number):
            result = NumericalDifferentiator.CentralDerivative(
                fForward, -2, out estimatedError);
            Console.WriteLine("  Derivative = {0}", result);
            Console.WriteLine("  Estimated error = {0}", 
                estimatedError);
            // Using the ForwardDerivative method does work:
            Console.WriteLine("Using forward differences:");
            result = NumericalDifferentiator.ForwardDerivative(
                fForward, -2, out estimatedError);
            Console.WriteLine("  Derivative = {0}", result);
            Console.WriteLine("  Estimated error = {0}", 
                estimatedError);
            
            // The FBackward function at the end of this file
            // is an example of a function that requires
            // backward differences for differentiation at
            // x = 2.
            RealFunction fBackward =
                new RealFunction(FBackward);
            Console.WriteLine("Using backward differences:");
            result = NumericalDifferentiator.BackwardDerivative(
                fBackward, 2, out estimatedError);
            Console.WriteLine("  Derivative = {0}", result);
            Console.WriteLine("  Estimated error = {0}", 
                estimatedError);

            //
            // Derivative function
            //

            // In some cases, it may be useful to have the
            // derivative of a function in the form of a 
            // RealFunction, so it can be passed as
            // an argument to other methods. This is very
            // easy to do.
            Console.WriteLine("Using delegates:");
            // For central differences:
            RealFunction dfCentral = 
                NumericalDifferentiator.CreateDelegate(
                    fCentral);
            Console.WriteLine("Central: f'(1) = {0}", 
                dfCentral(1));
            // For forward differences:
            RealFunction dfForward = 
                NumericalDifferentiator.CreateForwardDelegate(
                    fForward);
            Console.WriteLine("Forward: f'(-2) = {0}", 
                dfForward(-2));
            // For backward differences:
            RealFunction dfBackward = 
                NumericalDifferentiator.CreateBackwardDelegate(
                    fBackward);
            Console.WriteLine("Backward: f'(0) = {0}", 
                dfBackward(1));

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

        /// <summary>
        /// Function that requires the forward differences
        /// for numerical differentiation.
        /// </summary>
        private static double FForward(double x)
        {
            return (x+2) * (x+2) * Math.Sqrt(x+2);
        }

        /// <summary>
        /// Function that requires the backward differences
        /// for numerical differentiation.
        /// </summary>
        private static double FBackward(double x)
        {
            if (x > 0)
                return 1;
            else
                return Math.Sin(x);
        }
    }
}
Overview
Introduction
Features
Documentation
QuickStart Samples
Sample Applications
Downloads
Get it now!
Download trial version
How to Buy
Search

"The Extreme Optimization Statistics Library for .NET is a major boon for those doing statistical work in .NET. I strongly recommend this product."
- Marc Brooks

"I have made it my mission to institutionalize the value of good API design.  I strongly believe that this is key to making developers more productive and happy on our platform. It is clear that you value good API design in your work, and take to heart developer productivity and synergy with the .NET framework."
- Brad Abrams,
Lead Program Manager, Microsoft.

This is a partial list of companies who are using our libraries:
ABB Robotics
Allstate
Applied Materials
Arcam
Astra Schedule
Babson College
Canadian Council on Learning
Canyon Associates
Caxton Associates
CECity
Constellation Energy
CreditSights
DeepOcean
Duke University
Dynamotive
Elecsoft
Engelhard Corporation
Epcor
Equipoise Software
Galileo International
GAM UK
Gammex
GlaxoSmithKline
Global Matrix
The Hartford
Infinera Corporation
Intel
JDS Uniphase
LaBranche & Co.
Learning & Skills Council
Jacobs Consultancy
Litman Gregory
Lucas Systems
Malvern Instruments
Medrio
Merck & Co.
Mintera.
Monitor Software
MorningStar
NanoString Technologies
Paletta Invent
Parametric Portfolio Associates
Prosanos
RATA Associates
RiskShield
Ramboll
Standard & Poor's
Strategic Analysis Corporation
Univ. of Alicante
Univ. of South Carolina
vielife
Xerox
US Army