Review: C for Numerical Simulations
COS 323 - Computing for the Physical and Social Sciences
Topics
C Data types for Numerical Computation
When to reconsider: Running out of memory? Maybe int-arrays or
float-arrays will do the job too? But only consider this when
necessary.
Standard Math Operators
Arithmetic
- Divide: /
- Multiply: *
- Modulo: %
- Add: +
- Subtract: -
Pitfalls:
- ^ is exor, not power.
- % modulus may be different on different machines (signed or
unsigned). Better avoid it...
More Pitfalls:
- Constants: 5 is int, 5.0 is float. C has subtle conversion rules.
Example: double apple_quality = 4/5; Result: apple_quality == 0 (yikes!)
Use double apple_quality = 4.0/5.0 instead.
Rule of thumb: Result keeps data type when both inputs are of the same
type. It converts when to float when one is float.
Comparison
- Less than: <, <=
- Greater than: >, >=
- Not equal: !=
- Equal: ==
Pitfalls:
- = is not comparison but assigning a variable!!!
- if(my_float_variable == 0.0) ... is a bad idea. (Why?)
C Data Structures
1-D Arrays (also called Vectors)
Say you want to simulate the rottening behavior of apples. The
simulation considers 100 apples. Here's how to store them:
double apples[100];
- Tip: Don't sweat programming details in this course. Use constant size
arrays of the maximum size you use to get the job done. Programming
elegance and dynamic allocation can be dealt with when everything
works (and in another course!)
- Another tip: Programming styles that help.
/* At top of your program */
#define MAX_APPLES 100
/* Somewhere else */
double fresh_apples[MAX_APPLES];
double rotten_apples[MAX_APPLES];
Indexing and Initializing an Array
long i;
for(i=0; i
{
fresh_apples[i] = 1.0;
rotten_apples[i] = 0.0;
}
Pitfall: C array indices run from 0 to array size-1 i.e. fresh_apples
runs from 0 to MAX_APPLES-1. If you use MAX_APPLES or bigger numbers
you have a bug (which may be hard to find!).
2-D Arrays (or Matrices)
This time we happen to have an acre of apple trees:
#define X_APPLES 10
#define Y_APPLES 15
double apple_garden[X_APPLES][Y_APPLES];
Numerical Input and Output
Input
scanf ("%f", &x); Reads a float from standard
input and stores it in x.
scanf ("%lf", &x); Reads a double from
standard input and stores it in x.
scanf ("%Lf", &x); Reads a long double
from standard input and stores it in x.
Output
Letting afloat = 56.12345, the following output can be generated.
Function call example |
Sample Output |
Comments |
printf ("%e", afloat);
printf ("%10.2e", afloat);
printf ("%+10.2e", afloat); |
5.612345e+01
5.61e+01
+5.61e+01 |
printf ("%f", afloat);
printf ("%10.2f", afloat);
printf ("%+10.2f,%+10.2f", afloat, -afloat);
printf ("% 10.2f", afloat); |
56.12345
56.12
+56.12, -56.12
________56.12
|
C Standard Library Math Functions
There are numerous math functions available in the c standard library.
There are many variants of each function, however so review the following
carefully if you get stuck with strange numerical results!
For a comprehensive reference, see C: A Reference Manual by Samuel
P. Harbison and Guy L. Steele, Jr. Englewood Cliffs, NJ: Prentice Hall,
1995.
(Copies available in the E-quad library. Call Number: QA76.73.C15 H38 1995)
Absolute Value
int abs (int x); Returns the absolute value of an integer
x. Pitfall!! Use fabs for floats.
float fabs (float x); Returns the absolute value of a float
x.
long labs (long x); Returns the absolute value of a long
integer x.
Ceiling / Floor Function
double ceil (double x); returns smallest float-point number
equal to an integer not less than x.
double floor (double x); returns larger float-point number equal
to an integer not greater than x.
Exponential / nth Root Functions
double exp (double x); Returns e^x.
double pow (double x, double y); Returns x^y.
double sqrt (double x); Returns square root of x.
Logarithmic Functions
double log (double x); Returns the natural logarithm
of x.
double log10 (double x); Returns the base-10 logarithm
of x.
Trigonometric Functions
Note: All trig functions work with radians, not degrees.
Cosine related functions
double cos (double x); Calculates cosine of x.
double acos (double x); Calculates arccosine of x.
double cosh (double x); Calculates hyperbolic cosine of x.
Sine related functions
double sin (double x); Calculates sine of x.
double asin (double x); Calculates arcsine of x.
double sinh(double x); Calculates hyperbolic sine of x.
Tangent related functions
double tan (double x); Calculates tangent of x.
double atan (double x); Calculates arctangent of x.
double tanh (double x); Calculates hyperbolic tangent of x.
Notes on Performance
Some of the above math functions, especially transcendental functions,
may be considerably slower to execute than standard arithmetic operations.
If you use results from those functions repeatedly, storeing those values
in an array and accessing the array instead can dramatically increase performance.
Compiling
To compile your program inputfile.c to the executable outputfile use the following:
cc -o outputfile inputfile.c -lm
Instead of cc you can also use gcc or lcc. (Try which one gives you
the most useful error/warning messages.)
Warning: -lm is necessary when floating point arithmetic is used. But
most compiler will compile and will not complain if it's
missing. Results of calculations are just wrong!
Debugging
C programmers rule: Be thankful for a core dump. It's an array index
or pointer bug, which is nice enough to express itself!
What to do with bugs:
- Use printf's to find clues. What the magnifying glass was to Sherlock Holmes is printf to the debugging programmer.
- Use gdb. It can be used on core dumps to indicate the position of the problem (maybe).
- When getting desperate take a break and try again afterwards. Ask a friend to take a look. Send e-mail to the TA.
Tricks!
Horner's Method
Any polynomial in the form P(x) = ax^n + bx^(n-1) + ... dx + e can be expressed in a form requiring far less calculations:
P(x) = ax^3 + bx^2 + cx + d = x(x( ax + b ) + c) + d
The extremely naive approach of directly evaluating every power of x will cost you Deg Multiplications and Deg Additions whereas Horner's Method which rewrites P(x) in the right form,
Return COS 323 Main Page
Based on a Page Written July 15, 1998 by Hide Oki
and Modified September 10, 1998 by Roger Ahn
Written September 27, 1999 by Georg Essl