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/

Sunday, June 30, 2013

My First True Program: JerkMachine

Today I wrote a program. Truly, it was nothing significant. I tossed together bits of code to create a simple, useless construct. But it was rather enjoyable (when I was not frustrated beyond all reason), and I found it fairly useful (to a degree).
The program I wrote is fondly titled "JerkMachine". I built it for one function: to be rude and menacing to humans. There are no computations involved: my program does not count backward from 30 or give you integers in increments of two. It merely provides dialogue and accepts two responses from a user (two very simple responses). I wrote it for a fun little venture into how coding works and what tools are at one's disposal.
All of the code is based around character data types. I made a number of character date types (i.e name, greeting, firstinsult) as statements. For instance:

char greeting[] = "Hello, puny mortal! Cower before me! ";
char firstquestion[] = "Tell me- what is your name? ";

Some characters existed to serve as place-holders for a user's response:

char name[30];

Why did I give some of the characters values within the brackets and not others? That is a good question, and I am not so sure myself. From what I gathered in my reading, the numbers (as in char name[30]) give a certain number of places that the to-be-implemented name may take up (in this case, 30 spaces). The other characters (like char greeting[]) were not given values as they were directly equated to statements and thus had specific place values. Now, bear in mind that none of this may be entirely accurate. It will take me time to get proficient with all the terms and concepts behind even the base-level programming.

The remainder of the program is centered around input and output configurations. A "cout" marks where the program should spit out a certain something (string, integer, etc), and a "cin"marks where the user may enter a certain something. For "JerkMachine", the first of two user-input instances is when the user may enter his or her name, as seen below:

cin >> name;

Earlier, I had established "name" as a character. In addition to making name a valid character, I also enabled "name" to take up 30 spaces. In theory, anyone can enter their first name into the program and it will run properly.

However, the great kicker in this rousing example of pointless coding is the conditional. That is right, ladies and gentlemen: a conditional!
Conditionals are based on "if", "else", or "else if". In essence, they break down into true-or-false checks. For "JerkMachine", I wanted the user to be given two options for a reply: yes or no. One reply would beget a response from the program that differs from the other. I envisioned that it would be a fun little section to finish off the process. I was mistaken. For the longest time, I struggled to make the program function based on replies of "Yes" or "No". I will not go into details, but after establishing both "Yes" and "No" as characters and integers, and sometimes nothing at all, I found I could never get the "JerkMachine" to run properly. With experience I will be more comfortable with the various data types and control structures, but for today I was thoroughly confused.

The entire text-file for "JerkMachine" can be read below. Believe me when I say it functions. After a couple grueling hours of stupidity, it finally functions.
And I smile with senseless joy every time I run it.


"JerkMachine"
//Attempt at making a simple interactive program

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{

char name[30];
char greeting[] = "Hello, puny mortal! Cower before me! ";
char firstquestion[] = "Tell me- what is your name? ";
char firstinsult[] = "What a foolish name! I truly pity the incompetence of your species. ";
char secondquestion[] = "Now, answer me this- do you like computers? (Y/N) \n";
char response;

cout << greeting << "\n";
cout << firstquestion;
cin >> name;
cout << name << "! " << firstinsult << "\n";
cout << secondquestion;
cin >> response;
if (response == 'Y')
{cout << "\n" << "Well played, mortal. You have appeased me. You live a day longer." << "\n";}
else if (response == 'N')
{cout << "\n" << "Insolent mammal! You dare insult me in this fashion! Sleep with one eye open!" << "\n";}

return 0;
}

Thursday, June 27, 2013

Vim: The Beginning

Today, I began my journey into the world of vim. I experienced a rocky start, but some tutorial searches and a puzzle game later, I was surefooted and ready to really dig into text editing.

I was a little hesitant to engage with vim at first. From what I gathered in the classroom, I had the notion that it was a complex, intricate text editor that would require practice and discipline. I have since discovered that vim is more or less just that. However, I also garnered the notion that vim was an elegant and efficient method of text editing. This I will also attest to.
Given my incredible naivety with the world of programming, terminal digging, and file-writing, it is a rather bold claim to say that vim is beyond any other text editor in scope. But I like vim. It is a good editor, once you get to know it. I barely spent two hours with vim, yet I am expecting to spend plenty more learning its tips, tricks, ticks, and pure basic functions. Certainly a programmer is only as good as the tools he can wield, and I have established learning vim as a priority.

The two methods I was recommended to for learning vim are fairly distinct. One method is by utilizing a tutorial that is downloaded with the text editor. By typing "vimtutorial" in the terminal, one will be treated to a rather thorough, helpful, step-by-step breakdown of vim's essentials. I am just about halfway through the tutorial (I am a slow, slow man), but already I feel more confident in my vim-related endeavors.
The second path which programmers may take (or really, a supplement) is VIM Adventures. All at once an adorable, funny, retro, puzzle-game tutorial, VIM Adventures will encourage learning the text editor's functions and methods by progression. Theoretically, an individual will want to beat the game and save the world from the Bugs. But how might one go about becoming a hero? By learning vim! Of course, I got stuck on level three and decided to move on to different practice. I am pathetic, but the game is not, and it is worth checking out if only to admire the creative design elements of the gameplay.

Yes, this is a rather succinct post. I do not have much to discuss. Still, I must state once more how much I approve of vim, even if I do not fully comprehend its whole nature yet. Definitely consider learning it as a text editor, and definitely consider vimtutorial and VIM Adventures. I find it to be a step that one, as a programmer, should take. It is definitely in the right direction.

Link for game-tutorial: http://vim-adventures.com/

Also, for ubuntu users: if you want to acquire vim, open the terminal and type "sudo apt-get install vim". Boom.

Tuesday, June 25, 2013

Four Subjects on C++


 Information within this post is derived from the site http://www.cplusplus.com/
It is a valuable resource for beginner programmers.

Structure of a Program:
This introductory taste of C++ programming mirrors our practice in class. The task used in the example is that of writing a standard “Hello World!” sentence. Of course, I would spice it up with a comment such as “I am alive”, or “I am the harbinger of your destruction”, but that is personal preference.
As we discussed in class, the initial step for any programmer is to include a comment about the material he is writing. Comments are marked with // before the text. A more advanced version of the comment involves a block comment, notated with /* */. Unlike a regular comment, a block comment extends across lines until the end half */.
Everything grows more complicated from there. The step “#include <iostream>” is a message to the preprocessor. Essentially, this line is saying to the compiler that a file is going to be used from <iostream> in order to run the program. In our class, we utilized <stdio.h> instead, thus pulling a similar file from a different source.
Following with “int main ()”, which denotes that the main function of the program is about to be written. The brackets {} include the subsequent program. By writing “printf(“text”)”, you are telling the program to read off the text once it is run.
After writing the statement, a semicolon appears, marking the end of said statement. The “return 0;” statement tells the program to finish. Finish it all off with a deciding “}”.
Below are visual representations of the program covered above. Next, I will discuss a section on variables and data types, and will be markedly less involved than with this section.


1
2
3
4
5
6
7
8
9
10
// my first program in C++

#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World!";
  return 0;
}

1
2
// line comment
/* block comment */ 

Variables. Data Types.
The material in this section is rather lengthy and will be broken down on this blog. The initial topics are variables and identifiers. A variable is, basically, a value stored in the computer's memory, such as a=6 or a=b+1. The computer will remember these variables as values for reference.
An identifier is a string of letters, numbers, or underscore characters (_). Called variable identifiers, these formations can be used just as with the more simplistic versions.
Be aware that C++ recognizes various data types (characters, integers, boolean values). When C++ stores a variable, it condenses it into bytes (which can hold a range of representations from 0 to 255). Different values take up different numbers of bytes depending on size.
Variables can be declared by listing their variable type followed by the new declaration. As an example, to declare the variable a as an integer, one would write “int a”. Certain descriptions such as “long” and “unsigned” may be used in conjunction with a declaration such as “int”, but I will not delve into this concept.
An important matter to note is that variables can be declared as global or local. Global variables extend throughout a code in which it is declared, whereas local variables are viable only within their brackets {}.
In order for a variable to take on a definitive value, it must be initialized when it is declared. This may be accomplished through “=” or “()”. As an example, to declare that a=6, one would write either “int a = 6;” or “int a (6);”.
Lastly, there are strings. Strings are long variables that take up more than one character space (a string of characters, you could say). Strings are special in that, in order to be utilized, a special header must be included in the program (#include string). Subsequently, strings function like any other variable.
I apologize for the somewhat rushed nature of this section. Unfortunately, there are two more on their way.

Constants
Any individual with a middle school education will recognize that a constant is a fixed value. Within C++, there is a kind of constant called a literal, which is what most people would recognize. Literal constant are the obvious “a=6” variety. However, literals can be divided into five different varieties, but they are no complicated to discuss or comprehend.
Integer and floating point numbers are the first two literals. Obviously, integers consist of positive and negative values, while floating point numbers are less obviously composed of decimals and e characters (e.g 6.02e23).
Non-numerical literals follow, with character and string literals. Character literals are, you guessed it, single characters (a, b, c). Characters are notated with single quotes, as in 'a'. String literals are strings of characters (recall from a few sentences ago), and are represented with full quotation marks, as in “This is probably not too helpful”. A steady pattern may be noticed in the terminology that permeates C++.
Finally, there are boolean literals. These delightful intervals are adorable not only because their name, but because they represent one of two values: true or false.
Constants may be declared for the entirety of a program through the “#” header as a preprocessor directive. The proper heading is “#define” followed by the literal value.

Operators
At last, we come to the final material for this post: operators.
Assignment is the first major subject discussed. Broken down simplistically (though it is simple to begin with), assignment bestows a value with another value. Variables, constants, or so forth are what become assigned. One makes and assignment via the “=” sign. Assignments are read left to right, such that “a = 6” would assign a with a value of 6.
Arithmetic operators may be used, as well. These are “+, -, *, /”, and should be entirely comprehensible. The only non-obvious arithmetic operator is “modulo”, represented by “%”. Modulo gives the remainder of a division between two numbers.
Rational and equality operators are the next subjects of note. The inclusion of these operators (==, <, >, =<, >=, !=) will result in a boolean value of true or false. This may sound confusing, but consider how 5 = 5 may be true, but 2<1 is false. Care must be taken when working with these operators, however. It is important to include the double == when working with equality, as single = will denote an assignment (recall from earlier).
Logical operators are only slightly more complicated. These operators are composed of “!, &&, ||”, which represent Not, And, and Or. Three examples will be utilized to demonstrate the concepts behind these operators. With Not, the statement !(3 == 3) results in a false statement, because of the Not operator. With And, the statement ( (3 == 3) && (5 < 6) ) results in truth, whereas ( (3 == 3) && (6<5) ) is false, because the And operator sought to combine the two. Had we used the Or operator with the last statement, as in ( (3 == 3) || (6<5) ), the result would have been true because one of those statements is true.
Conditional operators are a bit more complex (at the far end of the simple spectrum). By utilizing the phrase “<condition> ? Result 1: Result 2”, one creates a conditional operator. If a conditional is true, Result 1 will show. If it is false, result 2 will show. To illustrate, take the conditional (2 == 5 ? 1:4). Since 2 is not equal to 5, the conditional is false, and Result 2 is selected (4).
There are a few more operators, but I will not be going over them within this post.


I am entirely uncertain as to whether writing all this was worth the time. I certainly have a stronger comprehension than if I had just read the material. However, if some stranger should happen upon this blog for information, the relative re-hash will likely be insufficient for quality understanding. Regardless, I am going to bed.

Sunday, June 23, 2013

Google and "Big Data"

The article “In Head-Hunting, Big Data May Not Be Such a Big Deal” contains information which will either thrill or discourage the reader. Composed of an interview with Laszlo Bock, a senior vice president of people operations at Google, the article reveals changing attitudes towards leadership qualities in job applicants and a shift in the perception of academic work. While the opinions and claims made by Bock are relative to the inner-operations at Google, they certainly carry weight and will no doubt become ever-increasing in other fields and industries. The question, then, is what the interview with Bock contains, and how one should feel about it. Certainly the ideas contained in the article reveal an intriguing progression in work management, but they also hint at the uncomfortable future of education and work.
            “Big Data” is brought up throughout the interview, which is essentially a compilation of information recorded by a company or organization that can be utilized in various ways (if I comprehend fully). Big Data is not unique to Google but is instead found across many areas and entities, especially business. Within the context of the interview, Big Data is referenced as the information which Google pulls from in analyzing applicants, workers, efficiency, and so on. The merits of a manager can be somewhat quantified by examining and evaluating worker opinions and quality of work. Yet the interview brings up the point that statistics and generalized data do not full help measure leadership qualities. Leadership is deemed “a more ambiguous and amorphous set of characteristics”, and while certain attributes like consistency may be measure, a touch of human insight is necessary.
            One cannot doubt the validity of certain sets of data and analysis. If a manager is poor at his job, there will be noticeable deficiencies in his region and the people he manages. When the feedback of employees regarding a manager is collected and compiled, there will likely be indications of a person’s effectiveness, ability, or character. But to break down human behavior into a faceless wall of information is not exactly a comforting or endearing concept. Big Data is useful, but care must be taken not to exclude those personal and, well, human qualities that might escape organized recordings and measurements.

            Still, data should be utilized, and will be increasingly useful as time progresses. The closing questions of the interview allude to this progression, as academics and the correlation between assets like G.P.A and test scores and compared against the ability of Google employees. When Bock states that “we’ve seen from all our data crunching is that G.P.A’s are worthless as a criteria for hiring”, a little bit of nervousness creeps into my mind. This is not because I rely on a G.P.A for self-assessment, but because there is a discrepancy between what the job market is starting to favor and what education is trying to instill. The remark that people who succeed in academic environments are “finely trained, they’re conditioned to succeed in that environment” is worrisome to an individual who succeeds in an academic environment. The statements expressed in the article are born of data relating academics to performance while working under Google, and a lack of correlation between the two. Notions of real-world skills and personal development are brought up to explain how useless something like a G.P.A is. Bock’s claims within the article spark a curiosity within me regarding the future of career application and formal schooling, while at the same time I am both intrigued and unsettled by the notion of Big Data, and wish to see how comprehensive it can truly become.