Common errors in Coursework 1
- ALWAYS
label graph axes and include appropriate units. For example, appropriate units for the energy vs time graphs you plotted in Coursework 1 are joules vs seconds. An appropriate unit is NOT the value of the loop variable. That is, for a loop "for (t=0;t<999; t++)" within which you calculated x[t] and v[t], some of you wrote t and not t*time_step to the file!
- When comparing numerical and analytical answers the following statements are NOT good enough:
"Not too far off………"
"Pretty close to…….."
"Almost exactly……."
You must quote your numerical result with an estimate of the error. For example, if the time step in your numerical solution is D t then - at the very best - you can only quote values accurate to ± (D t/2).
- Think carefully about the variables you declare - in particular,
ascertain whether you need
local or global variables (or constants).
For example, a considerable percentage of the class declared the
energy function as:
float energy (float, float, float, float);
and then passed F0, m, x[t] and v[t] to the function. F0 and m were used in at least two functions and thus it is inefficient to keep passing these variables to the function. Set them as globals or, in this case, better still #define F0 and m as constants.
- Try to make intelligent use of functions. All your code should not be contained in main() but, similarly, do not have almost every line of your code in a separate function. Think about what you want your code to calculate BEFORE you touch the keyboard. Structure your code so it is both efficient and readable.
- You MUST declare initial values. So, for example, x[0] and v[0]
must be defined for Coursework 1.
- Avoid repetition of code within 'if' blocks. For example, code
similar to the following appeared a number of times:
if (x[t]<0)
{
v[t+1]=v[t]+(F0/m)*time_step;
x[t+1]=x[t]+v[t]*time_step;
}
if (x[t]>0)
{
v[t+1]=v[t]-(F0/m)*time_step;
x[t+1]=x[t]+v[t]*time_step;
}
This is messy. You should rewrite the code as follows:
if (x[t]<0)
v[t+1]=v[t]-(F0/m)*time_step;
else
v[t+1]=v[t]+(F0/m)*time_step;
x[t+1]=x[t]+v[t]*time_step;
- The fabs() function may be used to get the absolute value of
a
floating point variable. abs() is used with integer variables.
- Make use of comments to explain key parts of your code. Look at the
example programs on the website to get a feel for how many comments you should include.
Back