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.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)