Subversion Repositories programming

Rev

Rev 171 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 171 Rev 173
Line 7... Line 7...
7
 * 2005-11-28
7
 * 2005-11-28
8
 * - Implement eval_euler() and eval_trapezoid().
8
 * - Implement eval_euler() and eval_trapezoid().
9
 *
9
 *
10
 * 2005-11-29
10
 * 2005-11-29
11
 * - Implement eval_romberg() and eval_simpson().
11
 * - Implement eval_romberg() and eval_simpson().
-
 
12
 * - eval_trapezoid() was giving horrible results, fix it.
12
 *
13
 *
13
 */
14
 */
14
 
15
 
15
#include <cmath>
16
#include <cmath>
16
#include <cstdio>
17
#include <cstdio>
Line 53... Line 54...
53
 
54
 
54
/**
55
/**
55
 * Evaluate the integral of the function given, over the interval given,
56
 * Evaluate the integral of the function given, over the interval given,
56
 * using the trapezoid method.
57
 * using the trapezoid method.
57
 *
58
 *
-
 
59
 * This is derived from the book's pseudocode on Pg 207.
-
 
60
 *
58
 * @param a the lower bound of the integral
61
 * @param a the lower bound of the integral
59
 * @param b the upper bound of the integral
62
 * @param b the upper bound of the integral
60
 * @param n the number of intervals to use
63
 * @param n the number of intervals to use
61
 * @param f the function to evaluate
64
 * @param f the function to evaluate
62
 */
65
 */
63
float eval_trapezoid (const float a, const float b, const int n, float(*f)(float))
66
float eval_trapezoid (const float a, const float b, const int n, float(*f)(float))
64
{
67
{
65
    const float h = (b - a) / n;
68
    const float h = (b - a) / n;
66
    float answer = 0.0, xi_last = 0.0, xi_now = 0.0;
69
    float sum = 0.0;
67
    int i = 0;
70
    int i = 0;
68
 
71
 
69
    xi_last = a + (i * h); // i = 0 here
72
    sum = (1.0/2.0) * (f(a) + f(b));
70
 
73
    
71
    for (i=1; i<=n; i++)
74
    for (i=1; i<=n-1; i++)
72
    {
-
 
73
        xi_now = a + (i * h);
75
        sum += f(a + (i * h));
74
        answer += (f (xi_last) + f (xi_now) * (xi_now - xi_last));
-
 
75
        xi_last = xi_now; // shift xi's
-
 
76
    }
-
 
77
 
76
 
78
    return answer;
77
    return h * sum;
79
}
78
}
80
 
79
 
81
/**
80
/**
82
 * Evaluate the integral of the function given, over the interval given,
81
 * Evaluate the integral of the function given, over the interval given,
83
 * using the Romberg method.
82
 * using the Romberg method.