Click here to Skip to main content
15,894,907 members
Articles / Programming Languages / C#

One dimensional root finding algorithms

Rate me:
Please Sign up or sign in to vote.
4.81/5 (14 votes)
23 Oct 2006CPOL4 min read 48.7K   1.3K   32  
A set of popular algorithms to solve the equation f(x)=0 in one dimension.
using System;
using System.Collections.Generic;
using System.Text;

namespace RootFinding
{
	public class FalsePositionRootFinder : RootFinder
	{
		public FalsePositionRootFinder(UnaryFunction f)
			: base(f) {
		}
		public FalsePositionRootFinder(UnaryFunction f,int niter,double pres)
			: base(f,niter,pres) {
		}
		protected override double Find() {
			double x1=m_xmin,x2=m_xmax,fl=m_f(x1),fh=m_f(x2),xl,xh,dx,del,f,rtf;
			if(fl*fh>0.0) throw new RootFinderException(m_RootNotBracketed,0,new Range(x1,x2),0.0);
			if(fl<0.0) {
				xl=x1;
				xh=x2;
			} else {
				xl=x2;
				xh=x1;
				Swap(ref fl, ref fh);
			}
			dx=xh-xl;
			int iiter=0;
			for(;iiter<m_NbIterMax;iiter++) {
				rtf=xl+dx*fl/(fl-fh);
				f=m_f(rtf);
				if(f < 0.0) {
					del=xl-rtf;
					xl=rtf;
					fl=f;
				} else {
					del=xh-rtf;
					xh=rtf;
					fh=f;
				}
				dx=xh-xl;
				if(Math.Abs(del)<m_Accuracy||f==0.0) return rtf;
			}
			throw new RootFinderException(m_RootNotFound,iiter,new Range(xl,xh),m_Accuracy);
		}
	}
}

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
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions