Click or drag to resize
DigitalRuneHow To: Solve a Non-Linear Equation

This section shows how to solve a non-linear equation.

Add DigitalRune.Mathematics namespaces

This example will use the class ImprovedNewtonRaphsonMethodF of the namespace DigitalRune.Mathematics.Analysis to find a solution for a linear equation. The samples will also use the type Numeric of the namespace DigitalRune.Mathematics. These namespace must be imported at the beginning of the source code file:

C#
using DigitalRune.Mathematics;
using DigitalRune.Mathematics.Analysis;
Solve a non-linear equation

We want to find an x that satisfies this non-linear equation:

4x³ - 5x² + 3x - 4 = 7, or

Foo(x) = 7 with Foo(x) = 4x³ - 5x² + 3x - 4

Therefore, we use the class ImprovedNewtonRaphsonMethodF. This class can solve the problem if the first order derivative of Foo(x) is known. In our case, the first order derivative is easy to compute as:

Foo'(x) = 12x² - 10x + 3

If the first derivative is not known, other classes of DigitalRune.Mathematics.Analysis can be used which implement root finding algorithms that do not require the first order derivative.

In our code we define methods for Foo(x) and Foo'(x):

C#
private static float Foo(float x)
{
  return 4 * x * x * x - 5 * x * x + 3 * x - 4;
}

private static float FooDerived(float x)
{
  return 12 * x * x  - 10 * x  + 3;
}

Then, we create an instance of the root finding algorithm:

C#
ImprovedNewtonRaphsonMethodF rootFinder = new ImprovedNewtonRaphsonMethodF(Foo, FooDerived);

Next, we need to define an interval [x0, x1] that contains the desired solution. Several solutions could exist for the linear equation and the interval defines in which solutions we are interested. We are looking for a solution near x = 0. The root finder can estimate an interval for us that contains the solution:

C#
float x0 = 0;
float x1 = 0;
rootFinder.ExpandBracket(ref x0, ref x1, 7);

The solution is then computed with

C#
float x = rootFinder.FindRoot(x0, x1, 7);

Finally, we check if the solution is correct. We use the class Numeric to test if Foo(x) = 7 as it should be. We could directly make the comparison with Foo(x) == 7 (in C#). But directly comparing floating-point numbers is not recommended because tiny numerical errors will cause Foo(x) to be, for example, 7.000007 - which is unequal to 7 but still within a reasonable tolerance.

C#
if (Numeric.AreEqual(Foo(x), 7))
  Console.WriteLine("Solution is correct.");
else
  Console.WriteLine("Solution is wrong.");