Thursday, July 29, 2010

Root Finding or finding Inverse function

Hello Friends,

In this post i will explain you how to get the inverse of a function or how to find the root of a function.
suppose there is a function y=f(x)
and you want the value of x when the y is 0 or something else.
you can find this solution using Numerical analytical mathamatics.
to use this algorithms.
download the source code from CodeProject
in this you will find a RootFinding.dll in source folder.
add reference of that file in your project.
and now you just need to make a class to use this dll.
RootFinder.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using RootFinding;

/// 
/// Summary description for RootFinder
/// 
public class RootFinder
{
    public RootFinder()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    // Newtons formel for iterativ lignings løsning
   private static double f (double x) {
        return (x*x-2*x+1); //replace this function by urs
    }
   public static double FindRoot(double x,double s,double e)
   {

       // Create the root finder object, that contains the algorithm

       BisectionRootFinder finder =
              new BisectionRootFinder(new UnaryFunction(f));

       // Define the accuracy you want for the root

       finder.Accuracy = 1.0E-04;

       // Prevent overflow

       finder.Iterations = 30;

       // Compute without bracketing outward
       try
       {
           return finder.Solve(s, e, false);
       }
       catch (Exception ex)
       {
           return FindRoot(0, s - 5, e + 5);
           //this was added letter on to expand the range of start value and end value.
       }
   }

}

you can call this method from your code using the following code
double temp=RootFinder.FindRoot(0,-1,1);

No comments:

Amitech

Hell0 Friends,
i know you are stuck with some serious problems and that's why you are here. So friends i m putting all the solved problems(with solution) that i have faced in my life (technical problems) on this blog.
In case you can not find the proper solutions, feel free to mail me at info@amitech.co
Amit Panchal