Subversion Repositories programming

Rev

Rev 155 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
154 ira 1
/* Copyright: Ira W. Snyder
2
 * Start Date: 2005-11-13
3
 * End Date: 2005-11-13
4
 * License: Public Domain
5
 *
6
 * Changelog Follows:
7
 *
8
 * 2005-11-13
9
 * - Implemented Functions 1-3 from the Project #3 Handout.
10
 * - Implemented Algorithm 7 (LaGrange) from Notes Set #3.
11
 * - Implemented Algorithm 8-9 (Newton Divided Diff) from Notes Set #3.
12
 *
13
 */
14
 
15
#include <cstdio>
16
#include <cmath>
17
using namespace std;
18
 
19
#define X_MIN = -5.0
20
#define X_MAX = 5.0
21
 
22
double func1 (double x)
23
{
24
    return 1.0 / (1.0 + pow(x, 2));
25
}
26
 
27
double func2 (double x)
28
{
29
    // NOTE: M_E is the value of e defined by the math.h header
30
    return (pow(M_E, x) + pow(M_E, -x)) / 2.0;
31
}
32
 
33
double func3 (double x)
34
{
35
    return pow(x, 14) + pow(x, 10) + pow(x, 4) + x + 1;
36
}
37
 
38
double LaGrangeMethod (double *x, double *y, int n, double point)
39
{
40
    double value = 0;
41
    double term  = 0;
42
    int i, j;
43
 
44
    for (i=0; i<n; i++)
45
    {
46
        term = y[i];
47
 
48
        for (j=0; j<n; j++)
49
        {
50
            if (i != j)
51
                term *= (point - x[j])/(x[i] - x[j]);
52
        }
53
 
54
        value += term;
55
    }
56
 
57
    return value;
58
}
59
 
60
double NewtonMethod (double *x, double *y, int n, double point)
61
{
62
    int i, j;
63
    double a[n];
64
 
65
    for (i=0; i<n; i++)
66
        a[i] = y[i];
67
 
68
    for (i=1; i<n; i++)
69
        for (j=n-1; j>=i; j--)
70
            a[j] = (a[j] - a[j-1]) / (x[j] - x[j-i]);
71
 
72
    // At this point, all of the a[i]'s have been calculated,
73
    // using a Divided Difference Table.
74
 
75
    double xterm = 1.0;
76
    double value = 0.0;
77
 
78
    for (i=0; i<n; i++)
79
    {
80
        value += a[i] * xterm;
81
        xterm *= (point - x[i]);
82
    }
83
 
84
    return value;
85
}
86
 
87
int main (void)
88
{
89
    double x[] = {-2, -1, 0, 2, 3};
90
    double y[] = {15, -3, -5, 15, 85};
91
 
92
    int size = 5;
93
    double point = 2.0;
94
 
95
    printf ("LaGrange = %e\n", LaGrangeMethod(x, y, size, point));
96
    printf ("Newton = %e\n", NewtonMethod(x, y, size, point));
97
 
98
    return 0;
99
}
100