Tuesday, January 7, 2014

A lot of work!

Many people think of coding as just typing a few lines of text into a computer and the job being done.  I knew so many kids when I was young that wanted to learn to make video games, thinking it would be the best job in the world.

What they never realized is how much work goes into a program.  I've only been programming a few weeks, and the programs I'm writing are still very small and impractical, but I'm sometimes amazed at how many steps it takes to do something that seems fairly simple.

One of my homework assignments recently asked me to write a program that calculates the distance between several points in 3D space using a function.  The thing I thought was interesting was the way you have to calculate the formula.

The formula to calculate the distance between the two points is:

This doesn't seem terribly complicated, and it really isn't, but the computer needs you to tell it how to solve the problem, step by step.  You can't just plug this in and expect the computer to know what to do.

The first thing I did was create the function, with 6 floating point parameters named after the variables in the formula.

float Distance(float ux, float uy, float uz,
 float vx, float vy, float vz)


The next step is to create 3 more variables to store the calculations from the subtractions inside the square root.  I initialized each of them immediately to be equal to the square of each subtraction.

 float x = powf(ux - vx, 2);
 float y = powf(uy - vy, 2);
 float z = powf(uz - vz, 2);


Finally I can create another variable to hold the total.  I initialize it to hold the square root of the sum of variables x, y, and z, and tell the function to return the result.

    float distance = sqrt(x + y + z);
    return distance;


Now we are ready to call the function in the program.  When you call the function, you'll give the program the numbers to use.  The order in which you type them is very important, or else the calculations will be off.

 cout << "The distance between (1, 2, 3,) and (0, 0, 0) = " << Distance(1, 2, 3, 0, 0, 0);
 cout << endl;

The entire program:

// 3D Distance
// Calculates the distance between two points in 3D space

#include 
#include 
using namespace std;

float Distance(float ux, float uy, float uz,
 float vx, float vy, float vz);

int main()
{
 cout << "The distance between (1, 2, 3,) and (0, 0, 0) = " << Distance(1, 2, 3, 0, 0, 0);
 cout << endl;

 cout << "The distance between (1, 2, 3,) and (1, 2, 3) = " << Distance(1, 2, 3, 1, 2, 3);
 cout << endl;
 
 cout << "The distance between (1, 2, 3) and (7, -4, 5) = " << Distance(1, 2, 3, 7, -4, 5);
 cout << endl;
}


float Distance(float ux, float uy, float uz,
 float vx, float vy, float vz)
{
 float x = powf(ux - vx, 2);
 float y = powf(uy - vy, 2);
 float z = powf(uz - vz, 2);

 float distance = sqrt(x + y + z);
 return distance;
}

No comments:

Post a Comment