Sunday, July 14, 2013

Trapezoidal Rule Code

I am including the code I wrote for the trapezoid rule integration assignment in this post. In addition to the original assignment, I incorporated an example of an array, per request. My original intent for usage of arrays fell through, and so I am attempting a weak make-up array display. For the sake of the reader, I will include comments besides a few of the lines.


#include <stdio.h>
#include <cmath>


double trapezoid (int n, float a, float b);             //Declaring both functions which will be utilized later
double f (float x);

int main() {

        float variable[2] = { 2, 6 };           //Creation of an array name "variable", with type float
        float a = variable[0];                  //Both a and b are assigned values of elements from the array
        float b = variable[1];                  //Array elements start at "0", so the array of two goes "0,1"
        double val;
        double answer = 32.0/3.0;
        double minErr = 1000;                   //These lines of code will be used to get an optimal n-value
        double err;
        int optimalN;
        double optimalVal;

        for( int n = 0; n < 5000; n++ ) {       //Creation of a for loop to work the integration

        val = trapezoid (n, a, b);

        err = std::abs(answer-val);

        if( err < minErr ) {                    //If statement that is used to capture and store the optimal values
            minErr = err;
            optimalN = n;
            optimalVal = val;
          }
        }

        printf ("The integral value = %f\n", val);
        printf( "minimum err = %f\n", minErr );
        printf( "Optimal n = %d\n", optimalN );
        printf( "Optimal val = %f\n", optimalVal );


        return 0;

}
                                                //It is considered good programming to define functions at the end- "prototyping"
double f (float x) {                            //Here, the first function is defined, with full parameters and statements

        return 4.0-(x-4.0)*(x-4.0);
        }

double trapezoid (int n, float a, float b) {    //The second function does all the integration

        double sum = 0;
        float step = (b-a)/n;
        float xi = a;

        for (int i = 0; i < n; i++) {       //This for loop integrates for each trapezoid of n, up to the max 5000
         sum += step*((f(xi+step)+f(xi))/2);
         xi += step;
         }
        return sum;

        }

Integration: Left-hand Rule against Trapezoid Rule

Two integrating heavyweights, the left-hand rule and the trapezoidal rule, met within a computer terminal today. Both were compiled, run, and compared against one another. Both members emerged relative equals.
The most recent class assignment was to create programs that found the integral value of an equation, f(x)=4-(x-4)^2. Two separate methods of finding the integral value, the left-hand rule and the trapezoidal rule, were permitted. The objective then relied on incorporating both rules into functions which could be utilized within a program. Though progress was rocky, painful, and harrowing, at last I had assembled programs (with assistance from a friend) which carried out the designated tasks.
Difficulty rested not in the premise of functions themselves, but in utilizing functions to perform calculus. I have yet to take a calculus class in school, and thus I was having to learn a new mathematical concept alongside computer science. However, I have emerged with a less vague understanding of integration than I previously possessed, and two rather spiffy programs.
When executed, both methods yield near identical results. Both were programmed to integrate with either 4000 rectangles or trapezoids. The optimal values, minimal error, and optimal value for n (number of rectangles or trapezoids) may be considered below.

Left-hand Rule:
integral value = 10.667030
minimum err = 0.000000
Optimal n = 1025
Optimal val = 10.666667
Trapezoid Rule:
The integral value = 10.667030
minimum err = 0.000000
Optimal n = 2049
Optimal val = 10.666667


 As can be seen, both yield identical integral values. However, they differ over the optimal number for n, with the trapezoid rule finding better success with a higher n-value.

Thursday, July 11, 2013

Functions and Arrays



From my most recent reading I have learned two things: my comprehension of new material is varying while my comfort with terminology and syntax is steadily improving. Let me explain.
                The topics regarding C++ which I just covered are functions and arrays. Functions are not tricky beasts to tame, especially if one has spent a year in any algebra class. The purpose of a function is that it may be called within a program to carry out a series of statements, or code, without crowding the main function. In fact, right in that previous sentence you realize you have been working with a function since the very beginning: the main function. All functions behave as the main function, as in they are called to carry out a series of statements. They can be defined, given parameters, some statements, and boom: ready to go.
                However, as the tutorial section Functions (II) has demonstrated to me, I am losing my reign over functions. Their capabilities slip from my grasp in the presence of referencing, while tricks such as default values and overloading do not appear, at the outset, useful to me. With time in class and with assignments, I am sure such concepts will become illuminated. And inline functions were a bit over my head. I grasp the gist of saving processing, but the entry keeps the topic unclear.
                Yet, in terms of recursivity I am relatively at peace. The concept of having a function call itself in performing its statements seems somewhat similar to the purposes of loops. I am also reminded of a somewhat humorous Saturday Morning Breakfast Cereal (a comic). The final entry on declaring functions presented itself as not challenge, and it was reminiscent of my instructor’s words regarding the topic. It is tidy, useful, and overall good programming to declare a function and then define it after the main function. Doing such will create cleaner code. This habit, known as prototyping, is one that will take some adjustment (“I want to define now!”), but should be worth it in the end.
                I am glad to finally read about arrays, for I have always scratched my head a bit at their reference. In prior weeks, I picked up the concept of arrays (as in they can store a range of values). Yet I had never really understood their structure, or syntax, or how they could be implemented in a program. Now, I might say, with some certainty, that I partially comprehend a fair portion of array basics.
                For instance, I now know that creating an array, such as “int array[6]” will enable me to store six integers within said array, and these integers can be used after the array’s declaration in several ways. Say I created “int array[6] (1,2,3,4,5,6,)”, and then grew partial to “array[3]”, which holds the value of 4 (in arrays, the values begin with place 0).  I could then establish that a variable, say a, is equivalent to this value which I have declared in the array, as in “array[3] = a”. Well done, I say. Now, what utility does this contain?
                At the moment, I am not one to say. Given some class time, I am bound to learn just how useful the creation and usage of arrays can become. I am bound to discover how complicated they can be, as multidimensional arrays come into play. Still, I have become more at peace with the concepts behind them, and that is something (probably). 

Links:
http://www.cplusplus.com/doc/tutorial/functions2/
http://www.cplusplus.com/doc/tutorial/arrays/
http://www.smbc-comics.com/