Each derivative has two overloaded methods: one for the function and another for the array of
data values. In order to calculate derivatives for a function, one has to pass a delegate function f(x), the value of x at
which the derivative is computed, and the increment h as input parameters.
On the other hand, in order to calculate derivatives for an array of data values, each method has input parameters which pass
the yarray values, the index called yindex which specifies the location at which the derivative is computed, and the
increment h. Here, the increment parameter is the value used to generate the function values.
The x increment defined as h = 1 and created the Y array of the sine function using this increment. Then calculated the first four
derivatives directly for the delegate function at x = 7. Derivatives for Y array also at x = 7, which corresponds to yindex = 7.
Running this example generates the results above. The reader will see that derivatives for the function and for the array values, as
expected, are almost identical. Slight differences only because numerical round-off error. Users can manipulate function and array
values.
Testing the Backward Difference Method
To test the Backward Difference method, a new static method has been added to show how to calculate
the first four derivatives for f(x) = Sin x. The TestBackwardMethod() method has
been written, added and executed:
static void TestBackwardMethod();
{
double h = 0.1;
double[] yarray=new double[10];
// create yarray:
for (int i = 0; i < 10; i++)
yarray[i] = f(i * h);
// Calculate derivatives for function:
double dy = Differentiation.Backward(f, 7, h);
listBox1.Items.Add("f'(x) = " + dy.ToString());
dy = Differentiation.Backward2(f, 7, h);
listBox1.Items.Add("f''(x) = " + dy.ToString());
dy = Differentiation.Backward3(f, 7, h);
listBox1.Items.Add("f'''(x) = " + dy.ToString());
dy = Differentiation.Backward4(f, 7, h);
listBox1.Items.Add("f''''(x) = " + dy.ToString());
// Calculate derivatives for array values:
foreach (double y1 in yarray)
listBox2.Items.Add(" " + y1.ToString());
dy = Differentiation.Backward1(yarray, 7, h);
listBox3.Items.Add("y' = " + dy.ToString());
dy = Differentiation.Backward2(yarray, 7, h);
listBox3.Items.Add("y'' = " + dy.ToString());
dy = Differentiation.Backward3(yarray, 7, h);
listBox3.Items.Add("y''' = " + dy.ToString());
dy = Differentiation.Backward4(yarray, 7, h);
listBox3.Items.Add("y'''' = " + dy.ToString());
}
static double f(double x)
{
return Math.Sin(x);
}
|