Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / C#

Automatic Differentiation using the AutoDiff Library

Rate me:
Please Sign up or sign in to vote.
4.94/5 (15 votes)
9 Apr 2011CPOL6 min read 33K   652   20  
Solving mathematical problems using the AutoDiff library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoDiff;

namespace NewtonRaphsonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // define and compile our function
            var x = new Variable();
            var func = TermBuilder.Exp(-x) + x - 2;
            var compiledFunc = func.Compile(x);

            // compute the two solutions
            var solution1 = NewtonRaphson(compiledFunc, -1);
            var solution2 = NewtonRaphson(compiledFunc, 2);

            Console.WriteLine("X1 = {0}, X2 = {1}", solution1, solution2);
        }

        static double NewtonRaphson(ICompiledTerm function, double x0, int iterationsCount = 10)
        {
            double x = x0;
            for (int i = 0; i < iterationsCount; ++i)
            {
                var valueAndGradient = function.Differentiate(x);

                // take the function's value - f(x)
                var fx = valueAndGradient.Item2;

                // we are dealing with single-variable functions. Therefore the first gradient element is the derivative
                var dfx = valueAndGradient.Item1[0];

                x = x - fx / dfx;
            }

            return x;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions