Thread: Arrays and the trapezoidal rule

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    1

    Question Arrays and the trapezoidal rule

    I need to write a program that reads data by declaring two arrays, and then use the appropriate looping to implement trapezoidal rule area calculations, i have pasted part of the program that i came up with, and the data is already declared in the arrays. please help asap!! thanks!

    # include <iostream>
    using namespace std;
    int main ()
    {
    int const n=14;
    int t[]={0,6,12,18,24,30,36,42,48,54,60,66,72,78,84};
    int s[]={124,134,148,156,147,133,121,109,99,85,78,89,104, 116,123};
    int acc=0;
    for (int i=1; i<n;i++)
    acc=acc+2*s[i];
    int area=0.5*6*(s[0]+acc+s[n]);
    cout<<"The distance is: "<<area;
    return 0;
    }

  2. #2
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    ah, just use the Fundamental Theorem of Calculus to find the definite integral Anyway, this kinda reaks of homework...I'll help a bit anyway.

    you either have an equation, f(x), or a set of data. Either works. If you have f(x), then you will want to determine what increments you are going to use for delta X (change in x/height of the trapezoid), determine the range that you are using, and then use a for loop to determine the value for f(x) at each value of x. If you already have the data, you can just skip that part. (it looks like you already have it)

    Now, the area of a trapezoid is given by the formula .5(b1+b2)*h, and in this case, the h is equal to delta X, your increment. B1 is equal to the value of f(x) at the left hand side of your trap, B2 is equal to the value of f(x) at the right hand side of the trap. Delta X is going to stay constant, so .5(h) is going to be a constant, multiplied by (b1+b2). (If you don't understand that, you shouldn't be doing calc without knowing the distributive property )

    So...calculate .5h. Then loop through your values for f(x) kinda like this...

    Code:
    float totalarea=0;
    
    for(float x=lowerendofrange; x<(upperendofrange-increment);x+increment)
    {
         b1=f(x);
         b2=f(x+increment);
         totalarea+=.5*increment*(b1+b2);
    }
    cout<<"The area under the curve is:"<<area;
    That isn't the complete program. You need to do a little bit of work with that, but it should be easy.


    oh...and one more thing... USE CODE TAGS!
    Away.

Popular pages Recent additions subscribe to a feed