$! to the pre‑compiled
"NAAUTIL.C" object code file.
$!
$! LINK
'P1', NAAUTIL, LNK$LIBRARY/LIB, LNK$LIBRARY_1/LIB
$!
$!
*******************************************************************
$! Create "NAAUTIL.OBJ" object code
by running the below step once.
$! Rember to re‑compile
"NAAUTIL.C" every time one of its flags
$! are changed.
$!
$! CC
/G_FLOAT NAAUTIL.C
$!
$!
*******************************************************************
8. The Equation Evaluator Routines
Over two-thirds of the algorithms in "Numerical
Analysis Algorithms in C" need to be compiled only once. They prompt for all the necessary
inputs. The other one-third of the
algorithms contain multiple modifiable functions, such as F(x). The C language has no pre-defined procedures
to allow functions to be entered at run-time.
To add these capabilities, a set of procedures have been written. These routines are located in the file named
"eqeval.c."
8.1 What the Routines Do
Quite simply, the equation evaluator routines allow
the user to enter mathematical equations at run-time rather than having to
recompile an algorithm for each unique function. All of the single function programs have the equation evaluator
routines already implemented into them.
These routines are activated only if the EQ_EVAL flag is set to TRUE in
"naautil.c." Implementing the
equation evaluator routines require only a few simple steps, as shown below.
A convenient utility program is also provided called
"ee.c." This program can be
used to familiarize yourself with writing equations in the C language. It can also be used as a command-line
calculator similar to the one the BASIC language provides. Like C, it uses infix notation. All math functions defined in the standard C
library header <math.h> are valid.
Unary operators like "+3" and "-3" are included if
the ANSI flag is set to TRUE in "eqeval.c."
To evaluate a function like "f(x) = cos(x + 3.14)
- 2", just type:
C:\NAA42>
ee cos(x + 3.14) - 2
Spaces are allowed inside the equations. Equations can be entered in uppercase or
lowercase characters. The variables x,
y and/or t can also be used inside the equations. The "ee" program will prompt you for the values of
needed variables. It also prompts you
to evaluate the entered equation again.
Typing "ee" by itself will cause the
equation evaluator to prompt for an equation to be entered.
All internal computations are done using
floating-point numbers. Equations are
limited to 130 characters as defined by MAX_LINE_SIZE in
"eqeval.c." This number may be
increased to suit your needs. The
larger it is, the more memory the routines will require. It was set to 130 since MS-DOS will not
accept more than 128 characters at the DOS prompt. Many computers have similar limitations.
8.2 How to Insert the Routines into a Program
To implement the equation evaluator routines into a
Numerical Analysis program, three simple modifications are required.
1) Make sure
that the EQ_EVAL flag is set to TRUE in "naautil.c."
#define EQ_EVAL TRUE
2) Add
something similar the following lines into the function to evaluate, usually
f(x):
if (eqeval)
return (eval_eq(x)); /* Use
the Equation Evaluator */
else
return (sin(x)); /* This is the
default function */
NOTE: Valid
calls to eval_eq() include eval_eq(any_number), eval_eq(x), eval_eq(x,y), and
eval_eq(x,y,t). Eval_eq() is not valid
unless at least one argument (parameter) is passed to it.
3) Just
after main(), add something like the following lines to print the correct
equation onto the screen and into the output file:
if (eqeval)
printf2("f(x) = %s", tmpstr);
else
printf2("%s", eq_text_f); /*
This is the default text */
8.3 An Example Using Simpson's Rule
See the file "041ee.c" for a descriptive
example using Algorithm 4.1 - Simpson's Rule for Integration and the equation
evaluator routines. This file performs
the same as "041.c", but is commented differently.
8.4 Using Eqeval.c As Pre-Compiled Object Code
If you find yourself using the equation evaluator
routines in "eqeval.c" rather frequently, you may want to compile
them only once and then link the object code to the programs.
If "naautil.c" had the EQ_EVAL flag set to
TRUE and is being used as object code, go no further with this section. The below steps are unnecessary in this
situation, since the "naautil.c" object code will already contain the
"eqeval.c" object code.
Otherwise, follow the five steps below:
1) Set the
EQEVAL_OBJ flag to FALSE in "eqeval.c":
#define EQEVAL_OBJ FALSE
2) Compile
"eqeval.c" into object code.
Do one of the following:
MS-DOS: C:\NAA42> CL /c EQEVAL.C - Creates "EQEVAL.OBJ"
UNIX: % cc -c eqeval.c - Creates "eqeval.o"
VAX/VMS: $ CC /G_FLOAT EQEVAL.C -
Creates "EQEVAL.OBJ"
3) Now set
the EQEVAL_OBJ flag to TRUE in "eqeval.c."
#define EQEVAL_OBJ TRUE
This keeps the algorithms from re-compiling the
equation evaluator routines. After step
2 above, "eqeval.c" should be available in object code to be linked
to later.
4) From now
on, compile the algorithms into object code.
Do one of the following, assuming "041.c":
MS-DOS: C:\NAA42> CL /c 041.C -
Creates "041.OBJ"
UNIX: % cc -c 041.c - Creates "041.o"
VAX/VMS: $ CC /G_FLOAT 041.C -
Creates "041.OBJ"
5) When
compiling the algorithms, be sure to link with the "eqeval" object
code. To do so, type one of the
following:
MS-DOS: C:\NAA42> CL 041 EQEVAL - Links "041.OBJ"
UNIX: % cc -o 041 041.o eqeval.o
-lm - Links "041.o"
VAX/VMS: $ LINK 041 EQEVAL -
Links "041.OBJ"
Under UNIX, steps 4 and 5 can be combined into the
single command "cc -o 041 041.c eqeval.o -lm".
See "cc.bat", "ccc" and
"vaxcc.com" in the UTIL sub-directory for ideas on automatically
linking object code to programs.
"cc.bat" is for MS-DOS, "ccc" is for UNIX and
"vaxcc.com" is for a VAX.
8.5 Valid Math Operators and Functions
This section lists what the equation evaluator
routines will accept and what they will reject.
Valid mathematical operators are:
* / % + - + -
(unary)
Invalid mathematical operators are:
** ^ mod rem \ div
Valid mathematical functions are:
abs() cos() frexp() sin()
acos() cosh() ldexp() sinh()
asin() exp() log() sqrt()
atan() fabs() log10() tan()
atan2() floor() modf() tanh()
ceil() fmod() pow()
Invalid mathematical functions are;
atof() atoi() div() hypot()
rand() fsin() fcos() ftan()
fasin() facos() fatan() fsinh()
fcosh() ftanh()
Valid variables are:
x y t (uppercase
or lowercase)
Valid number formats are:
3.1415 3.1415e-2 3 .4
For a brief description of the implemented
mathematical operators and functions, see Sections 5.1 and 5.2.
8.6 Sample Equations
Use the "ee" program to enhance your skills
at coding mathematical equations in C.
Some examples might be:
ee (1+2)*3
ee 1+2*3
ee 1 +
sin(x*2)
ee -2+3
ee
pow(3.0,x) - y + t
ee +1-x
ee x / y
ee
pow(x,pow(2.0,pow(2.0,y)))
8.7 Possible Error Messages
It is easy to accidentally enter an incorrect
equation. If an invalid equation is
encountered, one of several possible error messages will be printed to the
screen. The program will also
immediately abort. All possible error
messages are listed below:
1. "ERROR:
Parentheses are mismatched."
Bad Example: "((3)"
Checks for unmatched parentheses.
2. "ERROR:
Misuse of parentheses."
Bad Example: "1+2)*(3"
Another way to catch illegal usage of parentheses.
3. "ERROR:
"()" is not a valid equation."
Bad Example: "()"
Handles the special case of nothing enclosed in sets
of parentheses.
4. "ERROR:
Unrecognized mathematical operator encountered."
Bad Example: "3$4"
Only *, /, %, +, and - operators are allowed. The '^' symbol, shorthand for pow(), as in
"3^x" is not supported and is not part of C (catches former Pascal
users).
5. "ERROR:
Too many sequential unary operators used."
Bad Examples: "x ‑ ‑ ‑3"
and "+ ‑3"
Can usually have up to two unary operators without
errors, such as "3 + -4". No
more than one unary operator is allowed to start an equation or to follow a
left parenthesis.
6. "ERROR:
Incorrect equation entered. Check for
missing operands."
Bad Example: "3 * / 4"
Checks for numbers or functions missing between
operators.
7. "ERROR:
Incomplete equation entered."
Bad Example: "5+"
Checks for obviously incomplete equations.
8. "ERROR:
Invalid number in equation."
Bad Example: "3.1e‑r"
See valid number formats above. They are the same formats accepted by
printf("%f", &x);
9. "ERROR:
Invalid function in equation (1)."
Bad Example: "tangent(x)"
Checks for excessively large strings. Currently, any function longer than 5
characters (MAX_FUN_SZ) is too long.
You should increase the value assigned to MAX_FUN_SZ in
"eqeval.c" if you add any new functions longer than 5 characters.
10. "ERROR:
Invalid function in equation (2)."
Generated if you add more functions but forget to
modify isfunct() and/or you forget to define a new function ID, such as
POW_ID. You should never see this error
message if you do not modify the "eqeval.c" source code.
11. "ERROR:
In parser."
Generated if you add more functions but forget to
modify traverse_tree(), defining how the functions are to behave. You should never see this error message if
you do not modify the "eqeval.c" source code.
8.8 List of Algorithms Using the Equation Evaluator
Routines
The 34 algorithms below require only one function to
be evaluated. They each have the
equation evaluator routines already implemented into them. These algorithms need to be compiled only
once, assuming the EQ_EVAL flag was set to TRUE in "naautil.c.".
011B.c 031.c 041B.c 051B.c 080B.c
021.c 031B.c 041C.c 052.c 081.c
022.c 031C.c 041D.c 054.c 122.c
024.c 032.c 042.c 054B.c 122B.c
024B.c 034.c 043.c 054C.c 122C.c
025.c 035.c 043B.c 055.c 123.c
027.c 041.c 051.c 056.c
The 37 algorithms listed below require the input of
more than one function. Using the
equation evaluator on these algorithms is not recommended, since only one of
the multiple equations can use the equation evaluator routines at a time.
023.c 044C.c 101.c 113.c 125.c
024C.c 045.c 101A.c 113B.c 126A.c
033.c 045B.c 102.c 114.c 127A.c
040B1.c 045C.c 103.c 114B.c 128A.c
040B3.c 053.c 103B.c 115.c 129A.c
040C1.c 057.c 111.c 116.c
044.c 057B.c 112.c 121.c
044B.c 058.c 122B.c 124.c
The remaining 45 algorithms do not need function
equations (or the equation evaluator) and need to be compiled only once. Most of these perform matrix operations,
where the dimension of the matrices are entered at run-time and the memory is
dynamically allocated.
8.9 Limitations
The limitations of the equation evaluator routines are
as follows:
1. Only one
function can use the routines per program.
This means algorithms requiring only a single function, like f(x,y),
will benefit while algorithms requiring two or more functions, like f1(x,y) and
f2(x,y) in the same algorithm, will not benefit.
2. There is
a 130 character limit for the equations.
This can be easily overcome by increasing the value of #define
MAX_LINE_SIZE in "eqeval.c."
3. Up to 3
variables can be used in the equations.
These are: constants, x, y, and/or t.
These will cover all algorithms in this package which contain only a
single function. f(x) and f(y,t) are
the most common uses of these variables.
4. These
routines require the use of variable length arguments. Variable length argument functions can be
very non-portable. If your compiler
does not support variable length argument lists like "eval_eq(x, ...)",
you may need to fix the function eval_eq() to require all three arguments
(parameters) to be passed, such as eval_eq(x,y,t). Do this by replacing eval_eq() in "eqeval.c" with:
double eval_eq(x, y, t)
double x, y, t;
{
eq_eval_x = x;
eq_eval_y = y;
eq_eval_t = t;
traverse_tree(eq_node[0]);
return(eq_node[0]->value);
}
This alteration requires that all calls to eval_eq()
pass three values, such as:
f(x) --> eval_eq(x,0,0)
f(y,t) --> eval_eq(0,y,t)
8.10 Trade-Offs
PROS:
1. Adds
long-term flexibility. Algorithms which
use the equation evaluator routines need to be compiled only once.
2. Faster
than recompiling different functions, like f(x), several times.
CONS:
1. May
evaluate the function slightly slower than hard-coded functions. This may only become noticeable for very
large problem sets. Uses a binary tree
to evaluate the function rather than the faster and more optimized in-line
mathematical code generated by the compiler.
2. Will
make the executable code larger. The
equation evaluator routines can add up to 7K bytes of code to the executables.
9. Portability
It has been said that C is both "a relatively low
level system implementation language" and that "C is a portable
language." These two statements
seem contradictory. The portability of
C is very dependant upon the operating system, the compiler and even the
version of the compiler running the programs.
This chapter attempts to cover some of the necessary issues faced when
"porting" these algorithms to other computer platforms and
compilers. For further references about
portability, an excellent book detailing these issues is "Portability and
the C language", by Rex Jaeschke, 1988.
These algorithms are currently being used on a wide
variety of computer systems and compilers.
This chapter covers those platforms familiar to the programmer, namely:
MS-DOS on IBM PCs, UNIX workstations, Macintoshes, and VAX mainframes. These programs have been developed with
these platforms in mind, especially MS-DOS.
Care has been taken to keep these programs working on older K&R
compliant C compilers as well as the newer ANSI C compilers and even C++
compilers. If your compiler is fully
ANSI C compliant, then there should be no problems getting these programs to
work on your computer.
Whenever a peculiar problem arose on a non-ANSI
compiler, the best means of working around the problem was chosen while still
maintaining portability. This usually
took on the form of a special flag in "naautil.c." The sections below cover some of the
problems encountered and how they are or were overcome.
If you are unable to get these programs to run on your
computer system after reading this chapter and trying all means available to
you, you are welcome to call the programmer (Care-Free Software) for help or
return this package for a full refund.
Case Sensitivity
When uploading these programs to another machine,
remember that unlike FORTRAN, C is case sensitive! These algorithms will not work if they are translated into all
uppercase characters. This situation is
most likely to occur when using communications software to transfer the files
to a mainframe computer.
Memory Allocation
"Numerical Analysis Algorithms in C" relies
heavily upon the functions calloc() and free(). These are found inside most of the routines in "naautil.c",
"naautil2.c" and "naautil3.c". "Naautil.c" is used in every algorithm. If calloc() doesn't work, neither will the
algorithms. Calloc() usually requires
the <stdlib.h> header file.
Non-ANSI C compilers may use <malloc.h> or <alloc.h>.
If these do not do the trick, use the file
"calloc.c" found in the UTIL sub-directory. The comments inside this file explain how to use and implement it
into these programs. They provide the
functions naacalloc() and naafree() as replacements for calloc() and
free(). Few users should ever need
these replacement routines.
9.1 C vs ANSI C
The C language adopted a standard (ANSI C) in December
1989. Before this standard, the
definitive book on C was "The C Programming Language", first edition,
by Brian W. Kernighan and Dennis R. Ritchie, the creators of C. This older style of C is also referred to as
K&R style. For a simple summary of
the changes from C to ANSI C, see appendix C of the second edition of "The
C Programming Language."
ANSI C is guaranteed to accept any strictly conforming
program to generate portable code. To
obtain a copy of the ANSI C language specification, contact:
American
National Standards Institute
1430
Broadway
New
York, NY 10018
(212)
642-4900
Ask for ANSI X3.159-1989. The cost is fixed at $50.00 plus approximately $6.00 for
handling.
Function Prototyping
One of the features first used in C++ and quickly
adopted into ANSI C is the use of function prototypes. Function prototypes declare a function, its
expected input types and its expected output type. This is helpful for ensuring that functions are being used
correctly.
Most older C compilers do not understand the newer
type-checking prototype statements like:
double
*dvector(int, int); /* ANSI Style */
or
double
*dvector(int a, int b); /* ANSI Style */
These older compilers expect statements like:
double
*dvector(); /* K&R Style */
The new method of prototyping is preferred but not
usually necessary. Function prototypes
are usually placed at the top of a program or inside header files. To use the older method of prototyping,
simply change the ANSI flag to FALSE in "naautil.c." The default setting is TRUE for
ANSI-compliant C compilers.
Function Declarations
Functions can be declare in two different ways in ANSI
C. Examples of these two methods are
given below:
OLDER K&R STYLE NEWER ANSI STYLE
int max(a,b) int max(int a, int b)
int a,b;
{ {
... ...
} }
Both styles are allowed in ANSI C, however the ANSI
style is preferred. "Numerical
Analysis Algorithms in C" uses the older K&R style to retain
compatibility. You may restructure the
functions to conform with the newer ANSI style if necessary. Setting the ANSI_FUNCT flag to TRUE causes
several key functions to use the newer ANSI style function declaration. This is required when using THINK C 4.0 on a
Macintosh.
9.2 IBM PCs and MS-DOS
Microsoft C 5.0
All of these programs were developed using Microsoft C
5.0 with the small model library. If
you use anything other than the small model, add "#include
<malloc.h>" to the top of "naautil.c" and anywhere else
where alloc() and calloc() are used.
<malloc.h> is not part of ANSI C.
Use <stdlib.h> to replace it if possible.
Also, this compiler allows spaces to precede a
"#define" statement. This is
not standard and will not work on several UNIX compilers. This problem has been corrected. No leading white spaces are present before
"#define" statements in this version, even though using them would
have made some of the code easier to read.
Compile using the /Za switch to check for ANSI
compatibility.
Turbo C 2.0
No reported incompatibility problems.
9.3 UNIX Workstations
These programs should work on all UNIX
workstations. If the version of UNIX is
somewhat old, you may need to set the OLD_UNIX_OS flag to TRUE in the
"naautil.c" file. It allows
the use of <varargs.h> for variable length argument lists instead of
<stdarg.h>.
Using extended ASCII
Many of the algorithms use the extended ASCII
character set available on MS-DOS computers.
These get turned into unexpected characters when uploaded to many UNIX
machines. See Section 7.1 -
"Convert.c - Converting Files from Extended ASCII to Standard ASCII"
if this becomes a problem.
Variable Length Argument Lists
New to version 4.2 is the use of variable length
argument lists. The printf2() command
defined in "naautil.c" and the eval_eq() command defined in
"eqeval.c" are the only places where variable length argument lists
are used. The "printf2()"
function simply prints to two different places; to the screen and to a
file. It requires the ANSI header file
<stdarg.h>.
The header <stdarg.h> is an ANSI C invention
modeled closely on the UNIX <varargs.h> capability. Since ANSI C uses a slightly different
approach, the new header <stdarg.h> was designed rather than retaining
<varargs.h> with a changed meaning.
It is possible that some compilers will provide both of these headers,
while others might provide only one or the other.
If <stdarg.h> is provided, then use it over
<varargs.h>. If only
<varargs.h> is provided, then use the alternate printf2() inside
"naautil.c" by setting the OLD_UNIX_OS flag to TRUE. See the comments inside the printf2()
functions in Appendix B on how to use them.
AT&T UNIX PC
Some versions of this C compiler (older K&R style)
do not like multiple assignment expressions like "a = b = 4;". To overcome this problem, just break these
statements up like "b = 4; a = b;".
All of these kinds of statements have been found and corrected in
version 4.2. This compiler was used at
Brigham Young University's Numerical Analysis Laboratory in 1989.
HP 9000/300
Had an error when not leaving a space between an equal
('=') and a minus sign ('-').
Example: for
(i=-1;i<=N;i++). Fixed it by adding
a space. Example: for (i= -1;i<N;i++). This is probably due to an ambiguity with
the obsolete usage of "=-" for "-=", such as with x -= 1;
to represent x = x - 1;. All
occurrences of the above problem have been corrected in all of the algorithms.
Sanyo ICON
Version 4.0 was ported successfully onto a 68020 based
ICON in use at the Electrical Engineering Department at Brigham Young
University.
It had an older compiler that did not implement
"void." This can be
circumvented by adding "#define void int" or "typedef int
void;" to the top of "naautil.c."
Silicon Graphics 4D Series and the MIPS Compiler
Have had no problems running on a Silicon Graphics
4D/85GT using IRIX 3.3.1 and a MIPS C compiler.
Compile using the "-ansi" switch to check
for ANSI compatibility. The "-fullwarn"
switch may also be helpful in producing portable code.
9.4 Macintosh Computers
"Numerical Analysis Algorithms in C"
versions prior to 4.2 required command line redirection, such as "041 >
041.OUT". This presented a
problem, since Macintoshes do not have a command line! A quick-and-dirty fix in the past has been
to add the "ccommand()" function just after main(). Example:
(Use
the "ANSI" library in THINK C 4.0)
#include <console.h> /* Needed header file */
int ccommand (char ***p); /* Function prototype */
main(int argc, char **argv)
{
... /*
Declare variables first */
argc = ccommand(&argv); /*
Invokes a command line */
... /*
Continue w/the program */
}
This was only necessary for creating an output file
and has been corrected. All of the
programs have been rewritten to no longer need redirection, or the
"ccommand()" function.
9.5 VAX Mainframes
Many of the algorithms need the C Library function
"tolower()". Be sure it is
implemented correctly. You may need to
include the file <ctype.h> along with <stdlib.h>. "Tolower()" is usually implemented
as a function and as a macro. The
function in <stdlib.h> is preferred over the macro in <ctype.h>.
Another problem encountered was having the underscores
("_") stripped from file names after being transferred via kermit
(with ProComm) to a VAX. All underscore
characters have been removed from the file names eliminating this problem.
If your VAX C compilers does not perform
floating-point printing correctly in the printf() function, specify the
/G_FLOAT qualifier to the "CC" command.
Some VAX compilers do not support the "long
double" type. This type is used in
"naautil2.c" but is currently not used in any of the algorithms. Routines using "long double" types
in "naautil2.c" where placed there for completeness and for future
higher precision needs. To eliminate
any compiler errors or warnings, set the NO_LONG_DOUBLES flag to TRUE in
"naautil.c."
9.6 Tested Compilers
The following compilers have successfully run all of
the "Numerical Analysis Algorithms in C" v4.2 programs:
MS-DOS:
1. Microsoft C
5.0
2. Turbo C 2.0
UNIX:
1. MIPS C
Compiler for Silicon Graphics 4D Workstations
Macintosh:
1.
THINK C 4.0 (Set
ANSI_FUNCT == TRUE)
VAX/VMS:
1. VAX C v3.1
2. VAX C v3.2
The following additional compilers have successfully
run previous versions of the "Numerical Analysis Algorithms in C"
programs:
UNIX:
1. AT&T
UNIX PC
2. HP 9000/300
3. Sanyo ICON
VAX/VMS:
1. MicroVAX
10. Sample License Agreements
"Numerical Analysis Algorithms in C" is
available for individuals, universities and corporations. These sample license agreements are provided
as a reminder of your rights when using these programs. They also allow the legal departments of
universities and corporations to determine the scope of a site license before
actually purchasing one. Personalized
license agreements are sent with each order.
10.1 Individual License Sample
"NUMERICAL ANALYSIS ALGORITHMS IN C"
INDIVIDUAL LICENSE (SAMPLE)
This Individual License is issued to <INDIVIDUAL'S
NAME HERE>, on <DATE>, by CARE-FREE SOFTWARE under permission of
Harold A. Toomey, the proprietary owner.
 AS SUCH, IT IS
PROTECTED BY COPYRIGHT LAWS AND INTERNATIONAL TREATY.  COPYRIGHT
LAWS PROHIBIT MAKING ADDITIONAL COPIES OF THE SOFTWARE FOR ANY OTHER REASON.
   THIS AGREEMENT SHALL ALSO BE BINDING ON ANY
SUBSEQUENT, AUTHORIZED LICENSEE. IF YOU
DO NOT WISH TO AGREE TO THE TERMS OF THIS AGREEMENT, PROMPTLY RETURN THE
COMPLETE SOFTWARE PROGRAM PACKAGE, WITH THE DISK PACKAGE(S) UNOPENED, TO
CARE-FREE SOFTWARE WITHIN 90-DAYS TO RECEIVE A FULL REFUND. IF YOU HAVE ANY QUESTIONS CONCERNING THIS AGREEMENT,
CONTACT CARE-FREE SOFTWARE, 464 NORTH 750 EAST, LINDON, UT 84042, OR CALL (801)
785-0464.
LICENSE
1. CARE-FREE
SOFTWARE grants you the right to use one copy of the Software on a single-user
computer, or on a single terminal or workstation of a multi-user computer or
local area network. Each workstation or
terminal on a multi-user computer or local area network must be separately
licensed by CARE-FREE SOFTWARE. If the
software package contains both 3½" and 5¼" diskettes, you are
licensed to use only a single set of diskettes for your single user computer,
terminal or workstation; you are not licensed to use the other set of
diskettes.
2. You may not
sublicense, rent or lease the Software, but you may permanently transfer your
license to use the Software and accompanying materials by delivering to another
party the original diskettes and material comprising the software package,
including this numbered individual license, and by simultaneously destroying
all copies of the Software and accompanying materials in your possession. Such transfer terminates your license to use
the Software. The new recipient of the
Software and accompanying materials accepts this agreement and is licensed
under the terms of this Agreement upon initially using the Software.
3. The
Software includes several text files, over a hundred C source code files, and
their accompanying input and output files.
It is intended that those using the Software modify the C source code as
part of the learning process for numerical methods and analysis. Copies of this Software or self-modified
versions of the source code are not to be distributed for direct commercial
advantage without prior written consent from Harold A. Toomey through CARE-FREE
SOFTWARE.
4. CARE-FREE
SOFTWARE further grants you the right to make a backup/archival copy of the
software diskettes as set forth in the Notification of Copyright, above. You may not copy, transfer, or otherwise use
the Software except as stated in this agreement.
LIMITED 90-DAY WARRANTY/LIMITATION OF REMEDIES
CARE-FREE SOFTWARE will replace, at no charge,
defective diskettes that are returned within 90 days of the original date of
purchase. CARE-FREE SOFTWARE warrants
that the diskettes are free from defects in material and workmanship under
normal use and service for a period of ninety (90) days after receipt. Any implied warranty(ies) on the diskettes
is also limited to ninety (90) days. By
opening the sealed disk package, you agree that the only remedy available to
you will be a refund of the purchase price of this software program
package. Some states do not allow
limitations on duration of an implied warranty, so the above limitation may not
apply to you.
SUCH WARRANTIES ARE IN LIEU OF OTHER WARRANTIES
IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO THE
SOFTWARE AND THE ACCOMPANYING WRITTEN MATERIALS.  CARE-FREE SOFTWARE WILL NOT BE LIABLE FOR
ANY SUCH CLAIM BY ANY OTHER PARTY.
This limited warranty gives you specific legal
rights. Some states provide other
rights, and some states do not allow excluding or limiting implied warranties
or limiting liability for incidental or consequential damages. As a result, the above limitations and/or
exclusions may not apply to you.
Furthermore, some jurisdictions have statutory consumer provisions which
may supersede this section of the Agreement.
GENERAL
If any provision in this agreement shall be unlawful,
void, or for any reason unenforceable, then that provision shall be deemed
severable from this agreement and shall not affect the validity and
enforceability of the remaining provisions of this Agreement. This Agreement is governed by the laws of
the State of Utah.
 If for any reason
whatsoever, you are not satisfied with any product purchased from us, we want
you to return it to us within 90 days.
We will be glad to exchange the product or give your money back.
NAA42-9/91
10.2 University/Corporation Site License
Sample
"NUMERICAL ANALYSIS ALGORITHMS IN C"
UNIVERSITY/CORPORATION SITE LICENSE (SAMPLE)
This Site License is issued to
<UNIVERSITY/CORPORATION NAME HERE>, on <DATE>, by CARE-FREE
SOFTWARE under permission of Harold A. Toomey, the proprietary owner.
 AS SUCH, IT IS
PROTECTED BY COPYRIGHT LAWS AND INTERNATIONAL TREATY.   COPYRIGHT LAWS
PROHIBIT MAKING ADDITIONAL COPIES OF THE SOFTWARE FOR ANY OTHER REASON.

 THIS AGREEMENT SHALL ALSO BE
BINDING ON ANY SUBSEQUENT, AUTHORIZED LICENSEE. IF YOU DO NOT WISH TO AGREE TO THE TERMS OF THIS AGREEMENT,
PROMPTLY RETURN THE COMPLETE SOFTWARE PROGRAM PACKAGE, WITH THE DISK PACKAGE(S)
UNOPENED, TO CARE-FREE SOFTWARE WITHIN 90-DAYS TO RECEIVE A FULL REFUND. IF YOU HAVE ANY QUESTIONS CONCERNING THIS
AGREEMENT, CONTACT CARE-FREE SOFTWARE, 1376 NORTH 1100 EAST, AMERICAN FORK, UT
84003-3245, OR CALL<PHONE_NUMBER>.
LICENSE
1. CARE-FREE
SOFTWARE grants you the right to make unlimited copies of the Software on your
university/corporation owned single-user computers, terminals and workstations
of multi-user computers and on local area networks. Each workstation or terminal on a multi-user computer or local
area network need not be separately licensed by CARE-FREE SOFTWARE, so long as
they are owned by you, the university/corporation. You are licensed to use all sets of diskettes which are shipped
with the Software.
2. In
addition, CARE-FREE SOFTWARE grants your currently enrolled students,
employees, and faculty the right to copy the Software and accompanying manuals
for their use, such as for graduate research and for numerical methods
courses. These individual copies remain
part of this site license and do not belong to the students, employees, or
faculty. For individuals to retain a
legal licensed copy of the Software after they are no longer enrolled or
employed or teach at the university/corporation, they must purchase an
Individual License.
3. You may not
sublicense, rent or lease the Software, but you may permanently transfer your
license to use the Software and accompanying materials by delivering to another
university/corporation the original diskettes and material comprising the
software package, including this numbered site license, and by simultaneously
destroying all copies of the Software and accompanying materials in your
possession. Such transfer terminates
your license to use the Software. The
new recipient of the Software and accompanying materials accepts this agreement
and is licensed under the terms of this Agreement upon initially using the
Software.
4. The
Software includes several text files, over a hundred C source code files, and
their accompanying input and output files.
It is intended that those using the Software modify the C source code as
part of the learning process for numerical methods and analysis. Copies of this Software or self-modified
versions of the source code are not to be distributed for direct commercial
advantage without prior written consent from Harold A. Toomey through CARE-FREE
SOFTWARE.
5. CARE-FREE
SOFTWARE further grants you the right to make a backup/archival copy of the
software diskettes as set forth in the Notification of Copyright, above. You may not copy, transfer, or otherwise use
the Software except as stated in this agreement.
LIMITED 90-DAY WARRANTY/LIMITATION OF REMEDIES
CARE-FREE SOFTWARE will replace, at no charge,
defective diskettes that are returned within 90 days of the original date of
purchase. CARE-FREE SOFTWARE warrants
that the diskettes are free from defects in material and workmanship under
normal use and service for a period of ninety (90) days after receipt. Any implied warranty(ies) on the diskettes
is also limited to ninety (90) days. By
opening the sealed disk package, you agree that the only remedy available to
you will be a refund of the purchase price of this software program
package. Some states do not allow
limitations on duration of an implied warranty, so the above limitation may not
apply to you.
SUCH WARRANTIES ARE IN LIEU OF OTHER WARRANTIES IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO THE SOFTWARE AND THE
ACCOMPANYING WRITTEN MATERIALS.  CARE-FREE
SOFTWARE WILL NOT BE LIABLE FOR ANY SUCH CLAIM BY ANY OTHER PARTY.
This limited warranty gives you specific legal
rights. Some states provide other
rights, and some states do not allow excluding or limiting implied warranties
or limiting liability for incidental or consequential damages. As a result, the above limitations and/or
exclusions may not apply to you.
Furthermore, some jurisdictions have statutory consumer provisions which
may supersede this section of the Agreement.
GENERAL
If any provision in this agreement shall be unlawful,
void, or for any reason unenforceable, then that provision shall be deemed
severable from this agreement and shall not affect the validity and
enforceability of the remaining provisions of this Agreement. This Agreement is governed by the laws of
the State of Utah.
 If for any reason
whatsoever, you are not satisfied with any product purchased from us, we want
you to return it to us within 90 days.
We will be glad to exchange the product or give your money back.
NAA42-9/91
11. Packaging Information
To offer the most flexibility to the users,
"Numerical Analysis Algorithms in C" v4.2 is shipped on a variety of
floppy diskette sizes and capacities.
Too many files are included in this package to fit them on a single
diskette. See the appropriate list
below to determine how the files are placed on the different diskettes.
Diskettes are currently available only for IBM PCs and
Macintosh computers. Each shipment
comes with the following:
- Set
of Diskettes with Labels
-
Personalized License Agreement with a unique ID Number
- Free
Technical Support
The below items are available for an additional fee:
-
User's Manual
-
Examples Book
-
MS-DOS Executables
-
Macintosh Executables
The "*.C" source code support files listed
below include the following files:
complex.c naautil.c round.c
eqeval.c naautil2.c trunc.c
gaussj.c naautil3.c
These files need to be present on each diskette you
intend to run the algorithms from.
11.1 MS-DOS Diskettes
11.1.1 5¼" 1.2M High Density
Diskettes
Disk #1: "Readme.doc"
Essential Information Document
"*.C"
Source Code Support Files
Algorithm
Source Code for Ch. 1-12
"IN"
Sub-Directory Input Data Files
"OUT"
Sub-Directory Output Data Files
"UTIL"
Sub-Directory Utility Files
"LANGS"
Sub-Directory Multiple Language Examples
"Revhist.doc"
Revision History Document
Disk #2: "Usersman.doc"
User's Manual in ASCII Text
11.1.2 5¼" 360K Low Density
Diskettes
Disk #1: "Readme.doc"
Essential Information Document
"*.C"
Source Code Support Files
Algorithm
Source Code for Ch. 1-4
Disk #2: Algorithm
Source Code for Ch. 5-9
Disk #3: Algorithm
Source Code for Ch. 10-12
Disk #4: "IN"
Sub-Directory Input Data Files
"OUT"
Sub-Directory Output Data Files
"UTIL"
Sub-Directory Utility Files
"LANGS"
Sub-Directory Multiple Language Examples
"Revhist.doc"
Revision History Document
Disk #5: "Usersman.doc"
User's Manual in ASCII Text
11.1.3 3½" 1.44M High Density
Diskettes
Disk #1: "Readme.doc"
Essential Information Document
"*.C"
Source Code Support Files
Algorithm
Source Code for Ch. 1-12
"IN"
Sub-Directory Input Data Files
"OUT"
Sub-Directory Output Data Files
"UTIL"
Sub-Directory Utility Files
"LANGS"
Sub-Directory Multiple Language Examples
"Revhist.doc"
Revision History Document
Disk #2: "Usersman.doc"
User's Manual in ASCII Text
11.1.4 3½" 720K Low Density
Diskettes
Disk #1: "Readme.doc"
Essential Information Document
"*.C"
Source Code Support Files
Algorithm
Source Code for Ch. 1-9
Disk #2: Algorithm
Source Code for Ch. 10-12
"IN"
Sub-Directory Input Data Files
"OUT"
Sub-Directory Output Data Files
"UTIL"
Sub-Directory Utility Files
"LANGS"
Sub-Directory Multiple Language Examples
"Revhist.doc"
Revision History Document
Disk #3: "Usersman.doc"
User's Manual in ASCII Text
11.2 Macintosh Diskettes
11.2.1 3½" 800K Macintosh Diskettes
Disk #1: "Readme.doc"
Essential Information Document
"*.C"
Source Code Support Files
Algorithm
Source Code for Ch. 1-11
Disk #2: Algorithm
Source Code for Ch. 11-12
"IN"
Sub-Directory Input Data Files
"OUT"
Sub-Directory Output Data Files
"UTIL"
Sub-Directory Utility Files
"LANGS"
Sub-Directory Multiple Language Examples
"Revhist.doc"
Revision History Document
"Usersman.doc"
User's Manual in ASCII Text
12. Purchasing Information
There are two ways to legally purchase and use this
software. The first is by ordering it
directly from Care-Free Software. The
second is by copying it from a licensed user and mailing a $20.00 check for an
individual license. Both methods
provide you with the same product, assuming you do not copy an old version of
the software.
"Numerical Analysis Algorithms in C" is
written to be used by colleges, universities, and students. Knowing that the budgets of all three are
usually very limited, the prices are kept low enough to have this software
accessible by everyone. It is not
unusual for student to want these algorithms for use in their profession after
graduation.
12.1 $20.00 Club
The $20.00 Club is really quite simple. To join, just copy this software from
someone else and send Care-Free Software a check for $20.00. This offer only applies for individual
licenses, not for site licenses. In
exchange, Care-Free Software will send you an individual license, some diskette
labels, and keep you informed of enhancements and upcoming releases. The User's Manual and Examples Book are not
included, but can be purchased separately.
If you are a student attending a school which has not
yet purchased a site license, you should pay for these programs. The $20.00 Club is our way of allowing
students to take a class requiring these algorithms and be able to quickly and
easily have this software available to them.
The main difference is that you make your own diskettes and save a few
dollars doing so. This method is
commonly referred to as Shareware.
If you are a student currently enrolled at a college
or university which has purchased a university site license, you may copy and
use this software from the university computers for free. If you intend to use the programs on your
job after graduating, then you should purchase an individual license. See the sample university/corporation site
license in Chapter 10 - "Sample License Agreements" of this manual.
12.2 Order Form
An order form is provided for your convenience. Use it to ensure you have the most recent
version of this software.
ORDER
FORM
"NUMERICAL
ANALYSIS ALGORITHMS IN C"
A complete set of 116 stand-alone C programs have been
written for the text Numerical Analysis, Burden & Faires, 3rd and
4th edition. These programs include ALL
of the algorithms as well as all modifications required for most of the
homework exercises. The C source code
is thoroughly commented and easily modified.
The same source code runs on MS-DOS, UNIX, VMS, the Macintosh, and more!
For a FREE demo disk call 1-801-492-1526.
|
|
TO
ORDER CALL OR MAIL THIS FORM TO:
CARE-FREE
SOFTWARE
1376
North 1100 East
American
Fork, UT 84003-3245
Please Indicate Method of Payment:
Check _____
Purchase Order _____ C.O.D. _____
Name ______________________________________________________________
Address ______________________________________________________________
______________________________________________________________
Phone ______________________________________________________________
Please Send Me:
Individual Licenses:
_____ Version
4.2 on MS-DOS Disks $30.00
_____ Version
4.2 on Macintosh Disks $35.00
_____ Demo
Disk: MAC _____ DOS _____ FREE
_____ User's
Manual (170 pages) $20.00
_____ Examples
Book (670 pages) $65.00
Site Licenses:
_____
University/Corporation Packet $800.00
(Includes: Set of MS-DOS and Macintosh disks, a User's
Manual, an Examples Book, and a site license good for unlimited
campus/corporate use.)
Diskette Size:
_____ 5¼" (360K) _____
3½" (720K) _____ 3½"
(800K Macintosh)
_____ 5¼" (1.2M) _____
3½" (1.44M)
_______________
MERCHANDISE TOTAL (prices
include S&H)
_______________
C.O.D. Orders add $5.00
_______________
UTAH RESIDENTS add 6¼% Sales Tax
_______________
TOTAL
UNLIMITED CUSTOMER SUPPORT! 1-801-492-1526. (7/7/93)
References
Balfour, Alexander, "Programming in Standard
Fortran 77", North Holland, 1979.
Borenstein, Philip, "THINK C User's
Manual", Symantec Corporation, 1989.
Bourne, Philip E., "UNIX for VMS Users",
Digital Press, 1990.
Burden, Richard L., "Numerical Analysis",
third edition, PWS-Kent Publishing Company, 1985.
Burden, Richard L., "Numerical Analysis",
fourth edition, PWS-Kent Publishing Company, 1989.
Jaeschke, Rex, "Portability and the C
Language", Hayden Books, 1988.
Kernighan, Brian W., "The C Programming
Language", first edition, Prentice Hall Software Series, 1984.
Kernighan, Brian W., "The C Programming
Language", second edition, Prentice Hall Software Series, 1988.
Koffman, Eliot B., "Pascal, A Problem Solving
Approach", Addison-Wesley Publishing Company, 1982.
Mattson, Jeff, "THINK C, The Professional's
Choice, Standard Libraries Reference", Symantec Corporation, 1989.
"Microsoft C 5.0 Optimizing Compiler, Language
Reference, Microsoft CodeView, and Utilities", Microsoft Corporation,
1987.
"Microsoft C 5.0 Optimizing Compiler, Run-Time
Library Reference", Microsoft Corporation, 1987.
"Microsoft C 5.0 Optimizing Compiler, User's
Guide and Mixed-Language Programming Guide", Microsoft Corporation, 1987.
"Reference Manual for the Ada Programming
Language, ANSI/MIL-STD-1815A-1983", Meridian Software Systems, February
17, 1983.
Sideris, Daniel A., "VAX/VMS: Mastering DCL
Commands and Utilities", QED Information Sciences, Inc., 1990.
Tucker, Allen B., "Apple Pascal, A Programming Guide",
CBS College Publishing, 1982.
"Turbo Pascal, Version 3.0, Reference
Manual", Borland International, 1985.
APPENDIX A
C Source Code
for 041.C
|
|
Appendix A: C
Source Code for 041.C
/******************************************************************************
Composite
Simpson's Rule ‑ Algorithm 4.1
*******************************************************************************
!b
To
approximate the integral I = * f(x) dx:
"a
INPUT
endpoints a, b; even positive integer n; the function f().
OUTPUT
approximation XI to I.
NOTE:
Listed as Simpson's Composite Rule in 3rd edition of the text.
*******************************************************************************
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
3Q 1991, v4.2 *
******************************************************************************/
/*
** Set the EQ_EVAL flag to TRUE in
"naautil.c" to use the Equation Evaluator.
*/
#include
"naautil.c" /*
Numerical Analysis Algorithms Utilities. */
char
*outfile = "041.out"; /* Default name of the output
file. */
char
*eq_text_f = "f(x) = sin(x)"; /*
Needs updating $ */
/*****************************************************************************/
/* f(x) ‑
Function to evaluate, f(x). Needs
updating $. */
/*****************************************************************************/
double
f(x)
double x;
{
if (eqeval)
return (eval_eq(x)); /* Use the Equation Evaluator */
else
return (sin(x)); /* Use the default function. */
}
/*****************************************************************************/
main()
{
double a, b, h, X, XI, XI0, XI1, XI2, f();
int i, n;
/**********
* INPUTS *
**********/
NAA_do_first(outfile); /* NAA initialization
procedure. */
printf2("Composite Simpson's Rule ‑
Algorithm 4.1\n\n");
if (eqeval)
printf2("f(x) = %s", tmpstr); /* Print the Equation Evaluator text */
else
printf2("%s", eq_text_f); /* Print the
default equation text */
printf("\n\n");
printf("Enter endpoint a: ");
scanf("%lf", &a);
printf("Enter endpoint b: ");
scanf("%lf", &b);
fprintf(file_id, " from %lg to
%lg.\n\n", a, b);
do {
printf("Enter even number of
intervals on [a,b], n: ");
scanf("%d", &n);
if ((n <= 0) || (n % 2 != 0))
printf("ERROR ‑ n must be
even and positive.\n");
} while ((n <= 0) || (n % 2 != 0));
fprintf(file_id, "n = %d intervals on
[a,b].\n", n);
/*************
* ALGORITHM *
*************/
/* STEP #1 */
h = (b ‑ a)/n;
/* STEP #2 */
XI0 = f(a) + f(b);
XI1 = 0.0; /*
Summation of f(x(2i‑1)). */
XI2 = 0.0; /*
Summation of f(x(2i)). */
/* STEP #3 */
for (i=1;i<n;i++) {
/* STEP #4 */
X = a + i*h;
/* STEP #5 */
if (i % 2 == 0)
XI2 += f(X); /* For even i. */
else
XI1 += f(X); /* For odd i. */
}
/* STEP #6 */
XI = h*(XI0 + 2.0*XI2 + 4.0*XI1) / 3.0;
/***********
* OUTPUTS *
***********/
/* STEP #7 */
printf2("Interval number h =
%lg\n\n", h);
printf2(" !%lg\n", b);
printf2("XI = * f(x) dx = %.11lg\n", XI);
printf2(" "%lg\n\n", a);
printf2("Required %d functional
evaluations.\n", n+1);
NAA_do_last(outfile); /* NAA finish‑up
procedure. */
} /*
STOP */
/*****************************************************************************/
/* Copyright (C) 1988‑1991,
Harold A. Toomey, All Rights Reserved.
*/
/*****************************************************************************/
APPENDIX B
C Source Code
for NAAUTIL.C
|
|
Appendix B: C Source Code for NAAUTIL.C
/********************************
NAAUTIL.C ***********************************
"Numerical Analysis Algorithms in C" Utilities I
v4.2
******************************************************************************/
/*
** This source file contains many useful
procedures, some being used in all
** of the "Numerical Analysis Algorithms
in C" programs.
**
** At least three of the #defines are needed
for all of the supporting ".c"
** programs.
These #defines are: TRUE, FALSE, and ANSI. The supporting
** ".c" files are:
**
** naautil.c complex.c round.c
** naautil2.c eqeval.c trunc.c
** naautil3.c gaussj.c
**
** Many of these functions where derived from
the book "Numerical Recipes
** in C".
**
** "Naautil.c" contains the most
often used routines. Most are dynamic
** memory allocation routines used to create
very flexible vectors and
** matrices.
**
** "Naautil2.c" contains less
frequently used dynamic memory allocation
** routines to create very flexible vectors,
matrices, and cubes.
** Currently used only by: "081.c"
and "125.c"
**
** "Naautil3.c" contains routines for
complex vectors, matrices, and cubes.
** Currently used only by: "027.c",
"028a.c" and "081.c"
**
** This file should be included (only once!)
whenever the following
** procedures or functions are used:
**
** Return
Procedure
** Type
Name Description
** ‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
** void
naaerror ‑ Numerical Analysis Algorithms Error Handler
** int
printf2 ‑ Like printf() but writes to a file too
** void
NAA_do_first ‑ NAA initialization procedure
** void
NAA_do_last ‑ NAA final procedure
**
** int* ivector ‑ Allocates a 1‑D array of integers
** float* vector ‑ Allocates a 1‑D array of floats
** double* dvector ‑ Allocates a 1‑D array of doubles
** long double* ldvector ‑ Allocates
a 1‑D array of long doubles
** fcomplex* cvector ‑ Allocates a 1‑D array of fcomplex
**
** int** imatrix ‑ Allocates a 2‑D array of integers
** float** matrix ‑ Allocates a 2‑D array of floats
** double** dmatrix ‑ Allocates a 2‑D array of doubles
** long double** ldmatrix ‑
Allocates a 2‑D array of long doubles
** fcomplex** cmatrix ‑ Allocates a 2‑D array of fcomplex
**
** int*** icube ‑ Allocates a 3‑D array of integers
** float*** cube ‑
Allocates a 3‑D array of floats
** double*** dcube ‑ Allocates a 3‑D array of doubles
** long double*** ldcube ‑
Allocates a 3‑D array of long doubles
** fcomplex*** ccube ‑ Allocates a 3‑D array of fcomplex
**
** void
free_ivector ‑ Frees the allocated 1‑D array memory
** void
free_vector ‑ Frees the allocated 1‑D array memory
** void
free_dvector ‑ Frees the allocated 1‑D array memory
** void
free_ldvector ‑ Frees the
allocated 1‑D array memory
** void
free_cvector ‑ Frees the allocated 1‑D array memory
**
** void
free_imatrix ‑ Frees the allocated 2‑D array memory
** void
free_matrix ‑ Frees the allocated 2‑D array memory
** void
free_dmatrix ‑ Frees the allocated 2‑D array memory
** void
free_ldmatrix ‑ Frees the
allocated 2‑D array memory
** void
free_cmatrix ‑ Frees the allocated 2‑D array memory
**
** void
free_icube ‑ Frees the allocated 3‑D array memory
** void
free_cube ‑ Frees the allocated 3‑D array memory
** void
free_dcube ‑ Frees the allocated 3‑D array memory
** void
free_ldcube ‑ Frees the allocated 3‑D array memory
** void
free_ccube ‑ Frees the allocated 3‑D array memory
*/
/*********************/
/*
DEFINES AND FLAGS */
/*********************/
/*
** The FLAGS below allow the users more
flexibility when compiling and
** running these Numerical Analysis
Algorithms. They can also be used to
** make these programs more portable to
different computer systems.
*/
#define PI 3.14159265358979323846264338327950288419716939937510582097
#ifndef
FALSE
#define
FALSE 0 /* Define FALSE if not already
defined. */
#endif
#ifndef
TRUE
#define
TRUE !FALSE /* Define TRUE if not already
defined. */
#endif
#define ANSI TRUE /* Set to TRUE if using an ANSI C
standard */
/*
compliant compiler (default).
*/
/*
Set to FALSE if using an older C compiler */
/*
(Kernighan & Ritchie Style C).
*/
#define ANSI_FUNCT FALSE /* Set to TRUE if using ANSI's style
for */
/*
declaring functions. Set to FALSE
if */
/*
using K&R style functions (default).
*/
/*
(Set to TRUE if using THINK C 4.0 on a
*/
/*
Macintosh.)
*/
#define
TITLE_PROMPT TRUE /* Set to TRUE if you want to be
prompted */
/*
for an optional title at the start of
*/
/*
each program (default).
*/
/*
Set to FALSE to disable the title prompt. */
#define FILE_SAVE TRUE /* Set to TRUE to save output to a
file */
/*
(default).
*/
/*
Set to FALSE to create no output file.
*/
#define
EQ_EVAL FALSE /* Set to TRUE to be prompted for the use
of */
/*
the Equation Evaluator at run‑time.
*/
/*
Set to FALSE if entering f(x) inside the
*/
/*
C source code and re‑compiling it.
*/
/*
(default)
*/
#define NAAUTIL_OBJ FALSE /* Set
to TRUE if using "naautil.c" as a
*/
/*
pre‑compiled object code file to be
*/
/*
linked to at algorithm compile time.
*/
/*
Set to FALSE if using "naautil.c" as an */
/*
un‑compiled include file (default).
*/
/**********************
Computer System Specific Flags ***********************/
#define OLD_UNIX_OS FALSE /* TRUE
if running on older UNIX systems. */
#define
NO_LONG_DOUBLES TRUE /* TRUE if your C compiler does not
have */
/* the "long
double" type. */
/*
(Set to TRUE for most VAX C compilers)
*/
/*****************************************************************************/
#define MAX_LINE_SIZE 130 /* Largest input line size accepted. */
/* Set to
130 for MS‑DOS computers. */
/*****************
* INCLUDE FILES *
*****************/
#include
<math.h> /*
For math function prototypes.
*/
#include
<stdio.h> /*
For scanf(), printf() and fprintf().
*/
#include
<stdlib.h> /*
Needed for calloc(), free() and rand().
*/
#if
OLD_UNIX_OS == TRUE /*
For older UNIX C compilers */
#include
<varargs.h> /*
For vfprintf() used in printf2() */
#else
#include
<stdarg.h> /*
For vfprintf() used in printf2() */
#endif
/*
** NOTE: Including <ctype.h> for
tolower() may causes errors in Microsoft C
** 5.0 for IBM PCs where tolower() is defined
in the <stdlib.h> header file
** as well.
*/
/********************
* GLOBAL VARIABLES *
********************/
#if
NAAUTIL_OBJ == FALSE /* If
"naautil.c" is not pre‑compiled. */
FILE *file_id; /* Identifies the output file. */
char
tmpstr[MAX_LINE_SIZE]; /* A temporary string. */
int
eqeval = FALSE; /* Set if using the Equation Evaluator. */
#else /*
If "naautil.c" is pre‑compiled. */
extern FILE *file_id;
extern char
tmpstr[MAX_LINE_SIZE];
extern int
eqeval;
#endif
/***********************
* FUNCTION PROTOTYPES *
***********************/
#if ANSI
== TRUE /* ANSI STANDARD PROTOTYPING
(Post‑December 14, 1989)*/
void naaerror
(char error_text[]);
int printf2
(char *format, ...);
void NAA_do_first
(char *outfile);
void NAA_do_last
(char *outfile);
double** dmatrix (int a,
int b, int c, int d);
float** matrix (int
a, int b, int c, int d);
double* dvector (int
a, int b);
float* vector (int
a, int b);
int* ivector
(int a, int b);
void free_dmatrix
(double **m, int a, int b, int c, int d);
void free_matrix
(float **m, int a, int b, int c, int d);
void free_dvector
(double *v, int a, int b);
void free_vector
(float *v, int a, int b);
void free_ivector
(int *v, int a, int b);
double eval_eq
(double x, ...);
#else /* ANSI */ /*
OLDER STYLE PROTOTYPING (Pre‑December 14, 1989) */
/*
For compatibility with older C compilers.
*/
void naaerror();
int printf2();
void NAA_do_first();
void NAA_do_last();
double** dmatrix();
float** matrix();
double* dvector();
float* vector();
int* ivector();
void
free_dmatrix();
void free_matrix();
void free_dvector();
void free_vector();
void free_ivector();
double eval_eq();
#endif /* ANSI */
#if
NAAUTIL_OBJ == FALSE /* Include the
routines below only if the */
/*
NAAUTIL_OBJ flag is set to FALSE.
*/
/****************************
* EQUATION EVALUATOR LOGIC *
****************************/
#if
EQ_EVAL == TRUE /*
Needed for the Equation Evaluator's
*/
#include
"eqeval.c" /*
defines, global variables and functions */
#else /* EQ_EVAL */
#if ANSI
== TRUE
double
eval_eq (double x, ...) /* May need
this "dummy" procedure */
{
return 0.0;
}
#else
double
eval_eq (x, ...) /*
May need this "dummy" procedure */
double x;
{
return 0.0;
}
#endif /* ANSI */
#endif /* EQ_EVAL */
/***************
* SUBROUTINES *
***************/
/*****************************************************************************/
/*
naaerror() ‑ Numerical Analysis Algorithms standard error handler. */
/*****************************************************************************/
void
naaerror(error_text)
char
error_text[];
{
/* Print error message to the screen. (Standard error device) */
fprintf(stderr, "\n\"Numerical
Analysis Algorithms in C\" run‑time");
fprintf(stderr, " error...\n%s\n",
error_text);
fprintf(stderr, "...now exiting to
system...\n");
exit(‑1); /* Exit the program. */
}
#if
FILE_SAVE == FALSE
/*****************************************************************************/
/* Since
variable arguments are so terribly non‑portable, the below two */
/*
defines will allow the programs to work properly, but without the use of */
/* the
file_save option (or variable argument lists).
They turn printf2() */
/* into
tried‑and‑true printf() and they hide the usage of the file_id */
/*
variable by turning "fprintf(file_id, ...)" into
"sprintf(tmpstr, ...)". */
/* This
causes a write to an ignored string instead of to a file. */
/*****************************************************************************/
#define
printf2 printf /* For printf2()
*/
#define
fprintf sprintf /* For
fprintf(file_id, ...) */
#define
file_id tmpstr
#else /* FILE_SAVE == TRUE */
#if
OLD_UNIX_OS == TRUE /*
For older UNIX C compilers */
/*****************************************************************************/
/*
printf2() ‑ Like printf() but prints to the outfile (file_id) also,
if */
/* the FILE_SAVE flag is set to
TRUE. */
/* Use this printf2() instead of the
below printf2() if your C */
/* compiler does not have
<stdarg.h>, but does have <varargs.h>. */
/*
*/
/* NOTE: This code segment has not been tested. */
/*****************************************************************************/
/*
** printf2() ‑ OPTION #1 ‑‑
Uses #include <varargs.h>
*/
int
printf2(va_alist)
va_list
va_alist;
/*
or (w/out a ';')
va_decl
*/
{
va_list args;
char *format;
int length;
/* Note the one less parameter in va_start()
than in the below printf2() */
va_start(args);
format = va_arg(args, char*);
length = vprintf(format, args);
vfprintf(file_id, format, args);
va_end(args);
return length;
}
#else /* OLD_UNIX_OS */ /* For ANSI C compilers */
/*****************************************************************************/
/*
printf2() ‑ Like printf() but prints to the outfile (file_id) also, if */
/* the FILE_SAVE flag is set to
TRUE. */
/*****************************************************************************/
/*
** printf2() ‑ OPTION #2 ‑‑
Uses #include <stdarg.h>
*/
#if
ANSI_FUNCT == TRUE
int printf2(char
*format, ...)
#else
int
printf2(format, ...)
char
*format;
#endif
{
va_list args;
int length;
va_start(args, format);
length = vprintf(format, args); /* Prints to the screen (stdout). */
vfprintf(file_id, format, args); /* Prints to a file (file_id). */
va_end(args);
return length;
}
#endif /* OLD_UNIX_OS */
#endif /* FILE_SAVE */
/*****************************************************************************/
/*
NAA_do_first() ‑ Opens the output file if the FILE_SAVE flag is set
to */
/* TRUE, prints the NAA banner
to the screen and output */
/* file, then prompts for an
optional title and the */
/* optional Equation
Evaluator. */
/*****************************************************************************/
void
NAA_do_first(outfile)
char
*outfile;
{
int i;
#if
FILE_SAVE == TRUE /*
Set to TRUE if saving output to a file. */
/* Open the default output file initialized
in the main program. */
if ((file_id = fopen(outfile,
"w")) == NULL) {
sprintf(tmpstr, "Can not open the
output file named \"%s\".", outfile);
naaerror(tmpstr);
}
#endif /* FILE_SAVE */
/* Print the Numerical Analysis Algorithms
banner. */
for (i=1;i<80;i++) printf2("‑");
printf2("\n\t\t \"Numerical Analysis Algorithms in
C\" v4.2\n");
for (i=1;i<80;i++) printf2("‑");
printf2("\n\n");
#if
TITLE_PROMPT == TRUE
/* Prompt for an optional title to be placed
into the output file. */
printf("Enter an optional title [ie ‑
Set 2.1, Problem 2 a) ].\n‑‑‑‑>
");
fgets(tmpstr, MAX_LINE_SIZE, stdin);
/* Print the optional title to the output
file only if one was entered. */
if (tmpstr[0] != '\n')
fprintf(file_id, "%s\n",
tmpstr);
printf("\n");
#endif /* TITLE_PROMPT */
#if
EQ_EVAL == TRUE
get_eq(); /*
Get the equation and store it into "tmpstr." */
if (eqeval == TRUE) /* eqeval is set by get_eq().
If set, then */
parse_eq(); /* parse the equation into a usable
structure. */
#endif /* EQ_EVAL */
}
/*****************************************************************************/
/*
NAA_do_last() ‑ Closes the default output file and informs the user
of */
/* its creation or update. */
/*****************************************************************************/
void
NAA_do_last(outfile)
char
*outfile;
{
#if
FILE_SAVE == TRUE
if (fclose(file_id) == EOF) {
sprintf(tmpstr, "Can not close the
output file named \"%s\".", outfile);
naaerror(tmpstr);
}
printf("\nOutput saved into file
\"%s\".\n", outfile);
#endif /* FILE_SAVE */
}
/*****************************************************************************/
/*
dmatrix() ‑ Allocates a double matrix with range [a..b][c..d]. */
/*****************************************************************************/
double
**dmatrix(a,b,c,d)
int
a,b,c,d;
{
int i;
double **m;
/* allocate pointers to rows. */
m = (double **) calloc((unsigned) (b‑a+1),
sizeof(double*));
if (!m)
naaerror("allocation failure 1 in
dmatrix()");
m ‑= a;
/* allocate rows and set pointers to them.
*/
for (i=a;i<=b;i++) {
m[i] = (double *) calloc((unsigned) (d‑c+1),
sizeof(double));
if (!m[i])
naaerror("allocation failure 2 in
dmatrix()");
m[i] ‑= c;
}
return (m); /*
return pointer to array of pointers to rows. */
}
/*****************************************************************************/
/*
matrix() ‑ Allocates a float matrix with range [a..b][c..d]. */
/*****************************************************************************/
float
**matrix(a,b,c,d)
int
a,b,c,d;
{
int i;
float **m;
/* allocate pointers to rows. */
m = (float **) calloc((unsigned) (b‑a+1),
sizeof(float*));
if (!m)
naaerror("allocation failure 1 in
matrix()");
m ‑= a;
/* allocate rows and set pointers to them.
*/
for (i=a;i<=b;i++) {
m[i] = (float *) calloc((unsigned) (d‑c+1),
sizeof(float));
if (!m[i])
naaerror("allocation failure 2 in
matrix()");
m[i] ‑= c;
}
return (m); /*
return pointer to array of pointers to rows. */
}
/*****************************************************************************/
/*
dvector() ‑ Allocates a double vector with range [a..b]. */
/*****************************************************************************/
double
*dvector(a,b)
int a,b;
{
double *v;
v = (double *) calloc((unsigned) (b‑a+1),
sizeof(double));
if (!v)
naaerror("allocation failure in
dvector()");
return (v‑a);
}
/*****************************************************************************/
/*
vector() ‑ Allocates a float vector with range [a..b]. */
/*****************************************************************************/
float
*vector(a,b)
int a,b;
{
float *v;
v = (float *) calloc((unsigned) (b‑a+1),
sizeof(float));
if (!v)
naaerror("allocation failure in
vector()");
return (v‑a);
}
/*****************************************************************************/
/*
ivector() ‑ Allocates an integer vector with range [a..b]. */
/*****************************************************************************/
int
*ivector(a,b)
int a,b;
{
int *v;
v = (int *) calloc((unsigned) (b‑a+1),
sizeof(int));
if (!v)
naaerror("allocation failure in
ivector()");
return (v‑a);
}
/*****************************************************************************/
/*
free_dmatrix() ‑ Frees a matrix allocated with dmatrix(). */
/*****************************************************************************/
void
free_dmatrix(m,a,b,c,d)
double
**m;
int
a,b,c,d; /*
(variable d is never used.) */
{
int i;
for(i=b;i>=a;i‑‑)
free((char *) (m[i]+c));
free((char *) (m+a));
}
/*****************************************************************************/
/*
free_matrix() ‑ Frees a matrix allocated with matrix(). */
/*****************************************************************************/
void
free_matrix(m,a,b,c,d)
float
**m;
int
a,b,c,d; /*
(variable d is never used.) */
{
int i;
for(i=b;i>=a;i‑‑)
free((char *) (m[i]+c));
free((char *) (m+a));
}
/*****************************************************************************/
/*
free_dvector() ‑ Frees a double vector allocated by dvector(). */
/*****************************************************************************/
void
free_dvector(v,a,b)
double
*v;
int a,b; /*
(variable b is never used.) */
{
free((char *) (v+a));
}
/*****************************************************************************/
/*
free_vector() ‑ Frees a float vector allocated by vector(). */
/*****************************************************************************/
void
free_vector(v,a,b)
float *v;
int a,b; /*
(variable b is never used.) */
{
free((char *) (v+a));
}
/*****************************************************************************/
/*
free_ivector() ‑ Frees an integer vector allocated by ivector(). */
/*****************************************************************************/
void
free_ivector(v,a,b)
int
*v,a,b; /*
(variable b is never used.) */
{
free((char *) (v+a));
}
/*****************************************************************************/
#endif /* NAAUTIL_OBJ */
/******************************************************************************
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
3Q 1991, v4.2 *
* Copyright (C) 1988‑1991,
Harold A. Toomey, All Rights Reserved.
*
******************************************************************************/
APPENDIX C
Language Comparison Charts
|
|
Appendix C: Language Comparison Charts
This section is intended to
help those who have learned other languages other than C to transfer their
knowledge easily into C. The tables
provided should help in understanding and modifying the equations and code as
needed to perform numerical analysis.
These tables provide a simple comparison of items most likely to be used
in numerical analysis programs.
Complete working example
programs are also provided to give clear examples of how programs look in each
of the below languages.
The languages compared to C
include:
LANGUAGE COMPILER STANDARD
1. Ada Meridian Ada 4.1 ANSI/MIL‑STD‑1815A
2. BASIC Microsoft GW‑BASIC 3.20
3. C Microsoft C 5.0 ANSI C
4. C++ Borland Turbo C++ 2.0 AT&T C++ v2.0
5. FORTRAN 77 Microsoft FORTRAN 77 3.3 ANSI FORTRAN 77
6. Pascal Borland Turbo PASCAL 3.01A
(NOTE: '...' means one or more
statements).
C.1 C vs Ada
Description: C ADA
======================================================================
ARITHMETIC
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Addition + +
Subtraction ‑ ‑
Multiplication * *
Division / /
Modulus
(real) fmod(),
modf() N/A
Modulus
(integer) % MOD,
REM
Exponentiation pow() **
RELATIONAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Greater
Than > >
Greater
Then or Equal >= >=
Less
Than < <
Less
Than or Equal <= <=
Equal == =
Not
Equal != /=
LOGICAL
OPERATORS: (With
Bit_Ops; Use Bit_Ops;)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
And && AND
Or || OR
Not ! NOT
Xor N/A XOR
ASSIGNMENT
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Assignment = :=
Assignment
w/Add i += 2; I
:= I + (2);
Assignment
w/Sub i ‑= 4; I
:= I ‑ (4);
Assignment
w/Mult x *= ‑2.1; X := X * (‑2.1);
Assignment
w/Div x /= 8.9; X := X / (8.9);
Assignment
w/Mod x %= 7.3; X := X REM (7.3);
INCREMENT
AND DECREMENT STATEMENTS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Post‑Increment i++; I
:= I + 1;
Post‑Decrement i‑‑; I
:= I ‑ 1;
Pre‑Increment ++i; I
:= I + 1;
Pre‑Decrement ‑‑i; I
:= I ‑ 1;
DATA
TYPES: (With
Standard; Use Standard;)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char CHARACTER
String char
str[n]; str :
STRING(1..20)
‑or‑ STRING
Integer int INTEGER
Integer
with limits (use int) POSITIVE
(use
int) NATURAL
Long
Integer long
Floating
Point float FLOAT
‑or‑ REAL
Double‑Precision
Float double
Double
Double‑Precision long
double
Complex fcomplex
(naautil.c) (See the record below)
Arrays float
A[3][2]; A
: ARRAY (1..3,1..2)
of FLOAT;
Enumeration enum gender
{M,F}; type GENDER is (M,F);
Boolean BOOLEAN
Pointers int *ptr; PTR = ^INTEGER; ???
Structures struct complex { type COMPLEX_TYPE is
float r, i; RECORD
}; R, I : REAL;
END RECORD;
File
Pointers FILE
*fptr;
Examples of ADA type
declarations:
type
STRING is array (POSITIVE range <>) of
CHARACTERS;
type
INTEGER is range 1..2_000;
type
FLOAT is digits 16;
type
REAL is digits 16;
type
REAL is digits 16 range 0.0..1.0E35;
type
FIXED is delta 0.1 range 0.0..255.0;
DATA
TYPE INITIALIZATION: (With
Standard; Use Standard;)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch = 'c'; CH := 'c';
String char
*str = "A string"; STR :=
"A string";
Integer int
i = 5; I := 5;
Long
Integer int
i = 5L;
Floating
Point float
x = 123.4F; X := 123.4;
Floating
Point float
x = 1.0e‑2F; X := 1.0E‑2;
Double‑Precision
Float double x = 123.4;
Double‑Precision
Float double x = 1e‑2;
Double
Double‑Precision long
double x = 123.4L;
Double
Double‑Precision long
double x = 1e‑2L;
Complex fcomplex
c = {6.2,7.1};
Arrays float
A[3][2] = {{4,2},{1,‑2},{0,5}};
A(2,2)
:= ‑2;
Enumeration boolean ANS
= NO;
Boolean N/A BOOLEAN
FOUND;
FOUND
:= FALSE;
Pointers char * ^
Structures struct complex { RECORD1 := RECORD2;
float r = 12.0;
float i = 7.0;
};
File
Pointers FILE
*fptr;
Constants #define PI 3.1415
CONST PI = 3.1415;
const
char DOLLAR = '$'; CONST DOLLAR = '$';
(With
Unchecked_Conversion;)
DATA
TYPE CONVERSION: (Use Unchecked_Conversion;)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character (char) i CHARACTER(i);
String (char
*) x STRING(x);
Integer (int)
ch INTEGER(ch);
Long
Integer (long)
x
Floating
Point (float)
x REAL(x);
Double‑Precision
Float (double) x
Double
Double‑Precision (long
double) x
Complex (complex)
x COMPLEX(x);
Other
Types typedef
... new_type; type NEW_TYPE is ...;
(new_type)
x NEW_TYPE(x);
STANDARD
FUNCTIONS: (With
Math_Lib; Use Math_Lib;)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Truncation trunc() (in trunc.c)
Round round()
(in round.c)
Nearest
Integer ceil()
Nearest
Whole Number floor()
Absolute
Value abs(),
fabs() ABS()
Odd
(INTEGER) #define
ODD(a) (a%2)?(1):(0)
Square
Root sqrt() SQRT()
Square x*x X*X
Exponential exp() EXP()
Natural
Log log() LOG(X)
Common
Log log10() LOG(X,10)
Power pow(x,y) "**"(X,Y)
Sine sin() SIN()
Cosine cos() COS()
Tangent tan() TAN()
Cotangent 1.0/tan() COT()
Arcsine asin() ARCSIN()
Arccosine acos() ARCCOS()
Arctangent atan() ATAN(X)
Atan of
Quotient atan2() ATAN(X,Y)
Hyperbolic
Sine sinh() SINH()
Hyperbolic
Cosine cosh() COSH()
Hyperbolic
Tangent tanh() TANH()
Hyperbolic
Cotangent 1.0/tanh() COTH()
Hyperbolic
Arcsine ARCSINH()
Hyperbolic
Arccosine ARCCOSH()
Hyperbolic
Arctangent ARCTANH()
Hyperbolic
Arccotangent ARCCOTH()
Random
Number rand(),
srand()
SYNTAX:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Case
Sensitive? YES NO
Name a
program main() Procedure
Prog_Name is
{ begin
... ...
} end
Prog_Name;
Define
a Package use #include
"package_name.h"
Package
Prog_Name is
...
end;
Package
body Prog_Name
is
...
end
Prog_Name;
Comment
Begin /* ‑‑
Comment
End */ <CARRIAGE
RETURN>
Begin
Symbol { BEGIN
End
Symbol } END; ‑or‑ END function_name;
Statement
Terminator ; ;
Include
Files #include
<filename.h> With Package_name;
#include
"filename.h"
Variable
Names a‑zA‑Z0‑9_ A‑Z0‑9_
(31
chars max.) (?
chars max.)
Functions float func_name (int x,
y)
{
...
return some_float;
}
FUNCTION FNAME (X,Y: REAL) RETURN REAL is
...
RETURN SOMEREAL;
end FNAME;
Procedures proc_name
(int x, y)
PROCEDURE PROC_NAME(X,Y: REAL);
Get
Input scanf("%f",
&sum); READLN (SUM);
scanf("%s",
&string); GET (STRING_VAR);
scanf("%s",
&string); GET_LINE (STRING_VAR);
printf("\n");
scanf("%c",
&ch); GET (CH);
(With
Text_IO; Use Text_IO;)
Print
Output printf("A
= %f\n", A);
Float_IO.PUTLN ('A = ', A);
printf("A
= %f", A);
Float_IO.PUT ('A = ', A);
printf("S
= %s", S); PUT('S = ',
S); ‑or‑
printf("S
= %s\n", S); PUT_LINE('S = ', S);
printf("\n"); NEW_LINE;
printf("\n\n\n"); NEW_LINE (ITEM => 3);
May Need:
Package FIO is new float_io(float);
Package IIO is new integer_io(integer);
Package Ada_IO is new ...;
File
Output FILE *file_id;
file_id
= fopen("filename", "w");
...
fprintf(file_id,
"Any string here");
...
fclose(file_id);
...
...
Exit exit(1); Exit (Package_Name);
(Exits
main()) (Exits
Package_Name)
CONTROL
STRUCTURES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
If‑Then‑Else if
(x>y) { IF X
> Y THEN
... ...
(No
BEGIN/END needed)
} ELSIF
X = Y THEN
else
if (x==y) { ...
... ELSE
}
else { ...
... END
IF;
}
Case switch
(my_var) { CASE MY_VAR IS
case 'D' : WHEN 'D' =>
... ...
break; WHEN 'Y' | 'y' =>
case 'Y': ...
case 'y': WHEN OTHERS => NULL;
... END
CASE;
break;
default : break;
}
Loops while
(1) { LOOP
... ...
if (x==y) EXIT WHEN X = Y;
break; ...
... END
LOOP;
}
‑‑
or ‑‑
for
(;;) {
...
if (x==y)
goto exit_label;
...
}
exit_label:
While
Loops while
(count != 5) { WHILE count /= 5
LOOP
... ...
} END
LOOP;
For
Loops for
(i=1;i<=10;i++) { FOR I IN 1..10
LOOP
... ...
} END
LOOP;
for
(i=10;i>=1;i‑‑) { FOR
I IN REVERSE 1..10 LOOP
... ...
} END
LOOP;
Named
Loops N/A SUMMATION:
WHILE
COUNT /= 5 LOOP
...

C.2 C vs BASIC
Description: C BASIC
======================================================================
ARITHMETIC
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Addition + +
Subtraction ‑ ‑
Multiplication * *
Division
(float) / /
Division
(integer) / \
Modulus
(integer) % MOD
Exponentiation pow() ^
RELATIONAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Greater
Than > >
Greater
Then or Equal >= >=
Less
Than < <
Less
Than or Equal <= <=
Equal == =
Not
Equal != <>
LOGICAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
And && AND
Or || OR
Not ! NOT
Exclusive
Or N/A XOR
Implication N/A IMP
Equivalence == EQV
ASSIGNMENT
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Assignment = =
Assignment
w/Add i += 2; I
= I + (2)
Assignment
w/Sub i ‑= 4; I
= I ‑ (4)
Assignment
w/Mult x *= ‑2.1; X = X * (‑2.1)
Assignment
w/Div (float) x /= 8.9; X
= X / (8.9)
Assignment
w/Div (Int) N/A X = X \ (8.9)
Assignment
w/Mod x %= 7.3; X = X MOD (7.3)
INCREMENT
AND DECREMENT STATEMENTS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Post‑Increment i++; I
= I + 1
Post‑Decrement i‑‑; I
= I ‑ 1
Pre‑Increment ++i; I
= I + 1
Pre‑Decrement ‑‑i; I
= I ‑ 1
DATA
TYPES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch; DEFSTR C
(First
letter only)
‑or‑ C$
String char
str[n]; DEFSTR S
(First
letter only)
‑or‑ S$
Integer int
i,j; DEFINT
I,J
(First
letter only)
‑or‑ I, J
Long
Integer long
i;
Floating
Point float
x; DEFSNG X
(First
letter only)
‑or‑ X!
Double‑Precision
Float double x; DEFDBL X
(First
letter only)
‑or‑ X#
Double
Double‑Precision long
double x;
Complex fcomplex
(naautil.c)
Arrays int
A[3]; DIM A (3)
Enumeration enum
boolean {NO,YES};
Logical N/A
Functions N/A DEF
FNname(X)
(Prefix
with FN)
DATA
TYPE INITIALIZATION:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch='c'; CH$ =
"c"
String char
*str="string"; STR$ =
"string"
Integer int
i=5; I =
5% ‑or‑ I = 5
Long
Integer int
i=5L;
Floating
Point float
x=123.4F; X
= 123.4!, X = 123.4
-or-
X!=123.4
Floating
Point float
x=1.0e‑2F; X = 1.0E‑2
Double‑Precision
Float double x=123.4; X = 123.4#
Double‑Precision
Float double x=1e‑2; X = 1.0D‑2
Double
Double‑Precision long
double x=123.4L;
Double
Double‑Precision long
double x=1e‑2L;
Complex fcomplex
c={6.2,7.1};
Arrays int
A[3]={4,2,7};
Enumeration boolean
T=NO;
Constants const double x=123.4; PI# = 3.14
#define
PI 3.14 (Usage: X = 2 * PI#)
Logical N/A
DATA
TYPE CONVERSION:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character (char) x
String (char
*) x "Type
Mismatch" ERROR
Integer (int)
x CINT(X)
Long
Integer (long)
x
Floating
Point (float)
x CSNG(X)
Double‑Precision
Float (double) x CDBL(X)
Double
Double‑Precision (long
double) x
Complex (complex)
x
STANDARD
FUNCTIONS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Truncation trunc() (in trunc.c) FIX()
Round round()
(in round.c) CINT()
Nearest
Integer ceil()
Nearest
Whole Number floor() INT()
Absolute
Value abs(),
fabs() ABS()
Choose
Largest #define
MAX(a,b) (a)>(b)?(a):(b)
Choose
Smallest #define
MIN(a,b) (a)<(b)?(a):(b)
Square
Root sqrt() SQR()
Exponential exp() EXP()
Natural
Log log() LOG()
Common
Log log10() LOG(X)
/ LOG(10)
Sine sin() SIN()
Cosine cos() COS()
(Load
interpreter with
/D
option for doubles)
Tangent tan() TAN()
Arcsine asin() ATN(X/SQR(‑X*X+1))
Arccosine acos() ‑ATN(X/SQR(‑X*X+1))
+ 1.5708
Arctangent atan() ATN()
Atan of
Quotient atan2()
Hyperbolic
Sine sinh() (EXP(X)
‑ EXP(‑X))/2
Hyperbolic
Cosine cosh() (EXP(X)
+ EXP(‑X))/2
Hyperbolic
Tangent tanh() (EXP(X)
‑ EXP(‑X)) /
(EXP(X) + EXP(‑X))
Random
Number rand(),
srand() RND() (Returns 0..1)
SYNTAX:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Case
Sensitive? YES NO
Name a
program main()
Comment
Begin /* ' ‑or‑ REM
Comment
End */ <CARRIAGE
RETURN>
Begin
Symbol {
End
Symbol } END
Statement
Terminator ; <CARRIAGE
RETURN>
‑or‑ ':' followed by
another
command
Statement
Separator ; :
Include
Files #include
<filename.h> (Currently not
supported?)
#include
"filename.h"
Variable
Names a‑zA‑Z0‑9_ A‑Z0‑9.
(31
chars max.) (40
chars max.)
Functions float func_name (int x,
y)
{ DEF
FNfunc_name (X,Y) = SIN(X)
... (256
chars max.)
return sin(x); ‑or‑
}
(Load
interpreter with /N switch)
DEF
FNfunc_name (X,Y)
...
FNfunc_name = some_float
END
DEF
(Using
the /N switch)
Procedures proc_name
(int x, y) GOSUB proc_name
-or-
GOSUB line #
(Subroutines) { ...
... proc_name:
} ...
RETURN
‑or‑
(Load
interpreter with /N switch)
SUB
sub_name(x#)
...

printf("Sum
= \t%f\t.\n", sum);
PRINT
"Sum = ", SUM ,"."
printf("\n"); PRINT
File
Output FILE *file_id;
file_id
= fopen("filename", "w");
...
fprintf(file_id,
"Any string");
...
fclose(file_id);
100 OPEN "O", #1, "filename"
...
200 PRINT#1, "Any string."
...
300 CLOSE #1
Exit exit(1);
(Exits main())
RETURN ‑or‑ STOP
CONTROL
STRUCTURES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
If‑Then if
(x>y) { ... } IF (X
> Y) THEN ...
If‑Then‑Else if
(x>y) { ... } IF (X
> Y) THEN ... ELSE ...
else { ... }
(Load
interpreter with /N switch)
While
Loops while
(count != 5) { WHILE (logical)
... ...
} WEND
For
Loops for
(i=1;i<=11;i+=2) { FOR I = 1 TO 11
STEP 2
... ...
} NEXT
I
for
(i=1;i<10;i++) { FOR I = 1 TO
10‑1
... ...
} NEXT
I
for
(i=10;i>=1;i‑‑) { FOR I
= 10 TO 1 STEP ‑1
... ...
} NEXT
I
Case switch
(my_var) {
(Use
If‑Then‑Else or IF..GOTO)
case 'D' : IF
MY_VAR$ = "D" THEN 100
... IF
MY_VAR$ = "Y" THEN 200
break; IF
MY_VAR$ = "y" THEN 200
case 'Y': ...
case 'y': 100
...
... GOTO
400
break; 200
...
} GOTO 400
400
...

(Load
interpreter with /N
switch)
GOTO
my_mark
...
my_mark:
...
Goto
(Computed) N/A
ON
I GOTO 100,200,300
100
...
200
...
300
...
‑same
as‑
if
i==1 goto label1 IF I = 1 THEN
100
if
i==2 goto label2 IF I = 2 THEN
200
if
i==3 goto label3 IF I = 3 THEN 300
C.3 C vs C++
Description: C C++
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NOTE: Only additional operators
are listed, since "C" is a subset of "C++".
SYNTAX:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Comment
Begin /* //
Comment
End */ <NEWLINE>
(Needs
#include <stream.h> or <iostream.h>)
Get
Input scanf("%f",
&sum); cin >> sum;
scanf("%s",
&string); cin >> string;
scanf("%c",
&ch); cin >> ch;
(Needs
#include <stream.h> or <iostream.h>)
Print
Output printf("A
= %f\n", A); cout << A
<< "\n";
printf("A
= %f", A); cout << A;
printf("S
= %s", S); cout << S;
printf("S
= %s\n", S); cout << S
<< "\n";
printf("X
= %d", i+1); cout <<
"X = " << i+1;
printf("\n"); cout <<
"\n";
Use of
Objects C
= My_Matrix_Multiply(A,B);
C
= A * B;
X
= My_Complex_Multiply(C1,C2);
X
= C1 * C2;
C.4 C vs FORTRAN 77
Description: C FORTRAN 77
======================================================================
ARITHMETIC
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Addition + +
Subtraction ‑ ‑
Multiplication * *
Division / /
Modulus
(integer) % MOD(x,y)
Exponentiation pow() **
RELATIONAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Greater
Than > .GT.
Greater
Then or Equal >= .GE.
Less
Than < .LT.
Less
Than or Equal <= .LE.
Equal == .EQ.
Not
Equal != .NE.
LOGICAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
And && .AND.
Or || .OR.
Not ! .NOT.
Equivalent N/A .EQV.
Not
Equivalent N/A .NEQV.
ASSIGNMENT
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Assignment = =
Assignment
w/Add i += 2; I
= I + (2)
Assignment
w/Sub i ‑= 4; I
= I ‑ (4)
Assignment
w/Mult x *= ‑2.1; X = X * (‑2.1)
Assignment
w/Div x /= 8.9; X = X / (8.9)
Assignment
w/Mod x %= 7.3; X = MOD(X, 7.3)
INCREMENT
AND DECREMENT STATEMENTS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Post‑Increment i++; I
= I + 1
Post‑Decrement i‑‑; I
= I ‑ 1
Pre‑Increment ++i; I
= I + 1
Pre‑Decrement ‑‑i; I
= I ‑ 1
DATA
TYPES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch; CHARACTER*1 CH
CHARACTER
CH
String char
str[n]; CHARACTER*n
STR
CHARACTER
STR*n
Integer int
i,j; INTEGER
I,J
INTEGER*4
I,J
INTEGER*1
I,J
(Machine
dependant)
INTEGER*2
I,J
(Machine
dependant)
Long
Integer long
i; INTEGER*2
I
(Machine
dependant)
Floating
Point float
x; REAL X
REAL*4
X
Double‑Precision
Float double x; DOUBLE PRECISION X
REAL*8
X
Double
Double‑Precision long
double x;
Complex fcomplex
(naautil.c) COMPLEX C
Arrays int
A[3][2]; INTEGER
A(3,2) ‑or‑
INTEGER
A
DIMENSION
A(3,2)
Enumeration enum
boolean {NO,YES};
Logical N/A LOGICAL
A,B
DATA
TYPE INITIALIZATION: (Use variables
as declared above first)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch='c'; DATA
CH/'c'/
String char
*str="string"; DATA
STR/'string'/
Integer int
i=5; DATA I/5/
Long
Integer int
i=5L; DATA I/5/
Floating
Point float
x=123.4F; DATA
X/123.4/
Floating
Point float
x=1.0e‑2F; DATA X/1.E‑2/
Double‑Precision
Float double x=123.4; DATA X/123.4D0/
Double‑Precision
Float double x=1e‑2; DATA X/1.D‑2/
Double
Double‑Precision long
double x=123.4L;
Double
Double‑Precision long
double x=1e‑2L;
Complex fcomplex
c={6.2,7.1}; DATA C/(6.2,7.1)/
Arrays int
A[3][2]={{1,2},{3,4},{5,6}};
DATA
A/1,3,5,2,4,6/
Enumeration boolean
T=NO;
Constants const double x=123.4; REAL*8 X,PI
#define
PI 3.14 PARAMETER(X=123.4D0)
PARAMETER(PI=3.14)
Logical N/A DATA
A,B/.FALSE.,.TRUE.)/
DATA
TYPE CONVERSION:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character (char) x CHAR(X)
String (char
*) x
Integer (int)
x INT(X)
FORTRAN
66:
IFIX(X), IDINT(X)
Long
Integer (long)
x
Floating
Point (float)
x REAL(X)
FORTRAN
66:
SNGL(X), FLOAT(X)
Double‑Precision
Float (double) x DBLE(X)
Double
Double‑Precision (long
double) x
Complex (complex)
x CMPLX(X)
STANDARD
FUNCTIONS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Truncation trunc() (in trunc.c) AINT(), DINT()
Round round()
(in round.c) ANINT()
Nearest
Integer ceil() NINT(),
IDNINT()
Nearest
Whole Number floor() ANINT(),
DNINT()
Absolute
Value abs(),
fabs() ABS(),
IABS(),
DABS(),
CABS()
Choose
Largest #define
MAX(a,b) (a)>(b)?(a):(b)
MAX(),
MAX0(),
MAX1(),
DMAX1()
FORTRAN
66:
AMAX0(), AMAX1()
Choose
Smallest #define
MIN(a,b) (a)<(b)?(a):(b)
MIN(),
MIN0(),
MIN1(),
DMIN1()
FORTRAN
66:
AMIN0(), AMIN1()
Square
Root sqrt() SQRT(),
DSQRT(),
CSQRT()
Exponential exp() EXP(), DEXP(),
CEXP()
Natural
Log log() LOG(),
ALOG(),
DLOG(),
CLOG()
Common
Log log10() LOG10(),
ALOG10(),
DLOG10()
Sine sin() SIN(),
DSIN(), CSIN()
Cosine cos() COS(),
DCOS(), CCOS()
Tangent tan() TAN(),
DTAN()
Arcsine asin() ASIN(),
DASIN()
Arccosine acos() ACOS(),
DACOS()
Arctangent atan() ATAN(),
DATAN()
Atan of
Quotient atan2() ATAN2(,),
DATAN2(,)
Hyperbolic
Sine sinh() SINH(),
DSINH()
Hyperbolic
Cosine cosh() COSH(),
DCOSH()
Hyperbolic
Tangent tanh() TANH(),
DTANH()
Random
Number rand(),
srand()
SYNTAX:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Case
Sensitive? YES NO
Name a
program main() PROGRAM
prog_name
Comment
Begin /* 'C' ‑or‑ '*' in
column
1
Comment
End */ <CARRIAGE
RETURN>
Begin
Symbol {
End
Symbol } END w/any character
except
'0' or <SPACE>
in
column 6
Statement
Terminator ; <CARRIAGE
RETURN>
Include
Files #include
<filename.h>
$INCLUDE
: 'FILENAME.INC'
#include
"filename.h"
Variable
Names a‑zA‑Z0‑9_ A‑Z0‑9
(31
chars max.) (6
chars max.)
Functions float func_name (int x,
y)
{
...
return some_float;
}
REAL
FUNCTION FNAME (X,Y)
...
FNAME
= SOMEREAL
RETURN
END
‑or‑
FUNCTION
FNAME (X,Y)
REAL
FNAME
...
FNAME
= SOMEREAL
RETURN
END
Procedures proc_name
(int x, y) SUBROUTINE SUB_NAME (X,Y)
(Subroutines) { ...
...
WRITE
(4,8)
FORMAT
('1',2X,'Any string',/)
...
CLOSE
(4)
Exit exit(1);
(Exits main())
RETURN ‑or‑ STOP
CONTROL
STRUCTURES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
If‑Then if
(x>y) { IF
(X.GT.Y) THEN
... ...
} ENDIF
If‑Then‑Else if
(x>y) { IF
(X.GT.Y) THEN
... ...
} ...
else
if (x==y) { ELSE IF (X.EQ.Y)
THEN
... ...
}
else { ELSE
... ...
} ENDIF
Arithmetic
If if
(x>y) ... (For FORTRAN 66
compatibility)
IF
(X.GT.Y) ...
(limited)
(Not
in ANSI FORTRAN 77)
While
Loops while
(count != 5) { DO WHILE (logical)
... ...
} END
DO
For
Loops for
(i=1;i<=11;i+=2) { DO 30 I=1,11,2
... ...
} 30
CONTINUE
for
(i=10;i>=1;i‑‑) { DO
30 I=10,1,‑1
... ...
} 30
CONTINUE
Case switch
(my_var) { (Use If‑Then‑Else)
case 'D' :
...
break;
case 'Y':
case 'y':
...
break;
}
Goto
(Logical) goto
label_text; GOTO S1
(S1
is in [1..99999])
... ...
label_text
: S1 ...
(S1
is in col 1‑5)
...
Goto
(Computed IF) N/A (For FORTRAN 66
compatibility)
GOTO
(S1, S2,...Sn) I
S1
...
S2
...
Sn
...
‑or‑
(For
FORTRAN 66 compatibility)
GOTO
I, (S1, S2,...Sn)
S1
...
S2
...
Sn
...
‑same
as‑
if
i==1 goto label1 IF (I.EQ.1) GOTO
S1
if
i==2 goto label2 IF (I.EQ.2) GOTO
S2
if
i==n goto labeln IF (I.EQ.n) GOTO
Sn
Goto
(Arithmetic IF) N/A (Use
is discouraged)
IF
(arith_exp < 0) S1, S2, S3
‑same
as‑
IF
(arith_exp < 0) GOTO S1
IF
(arith_exp = 0) GOTO S2
IF
(arith_exp > 0) GOTO S3
C.5 C vs Pascal
Description: C Pascal
======================================================================
ARITHMETIC
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Addition + +
Subtraction ‑ ‑
Multiplication * *
Division
(real) / /
Division
(integer) / DIV
Modulus
(real) fmod(),
modf() N/A
Modulus
(integer) % MOD
Exponentiation pow() ‑‑‑
NOT STANDARD ‑‑‑
RELATIONAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Greater
Than > >
Greater
Then or Equal >= >=
Less
Than < <
Less
Than or Equal <= <=
Equal == =
Not
Equal != <>
LOGICAL
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
And && AND
Or || OR
Not ! NOT
ASSIGNMENT
OPERATORS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Assignment = :=
Assignment
w/Add i += 2; I
:= I + (2);
Assignment
w/Sub i ‑= 4; I
:= I ‑ (4);
Assignment
w/Mult x *= ‑2.1; X := X * (‑2.1);
Assignment
w/Div x /= 8.9; X := X / (8.9);
Assignment
w/Mod x %= 7.3; X := X MOD (7.3);
INCREMENT
AND DECREMENT STATEMENTS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Post‑Increment i++; I
:= I + 1;
Post‑Decrement i‑‑; I
:= I ‑ 1;
Pre‑Increment ++i; I
:= I + 1;
Pre‑Decrement ‑‑i; I
:= I ‑ 1;
DATA
TYPES: (Precede
with VAR)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char CHAR
String char
str[n]; STRING[n]
char
* (pointer only) STRING
(default
size of 80)
Integer int INTEGER
Long
Integer long
Floating
Point float REAL
Double‑Precision
Float double
Double
Double‑Precision long
double
Complex fcomplex
(naautil.c) (Create a record)
Arrays float
A[3][2]; A
: ARRAY [1..3,1..2]
OF
REAL
Enumeration enum
boolean {NO,YES}; TYPE ANS
= (NO, YES);
Boolean BOOLEAN
Pointers int *ptr; PTR = ^INTEGER;
Structures struct complex { TYPE COMPLEX_TYPE =
RECORD
float r, i; R, I : REAL
}; END;
File
Pointers FILE
*fptr; TEXT
Ranges I
: 1..80;
DATA
TYPE INITIALIZATION:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character char ch = 'c'; CH := 'c';
String char
*str = "A string"; STR := 'A
string';
Integer int
i = 5; I := 5;
Long
Integer int
i = 5L;
Floating
Point float
x = 123.4F; X := 123.4;
Floating
Point float
x = 1.0e‑2F; X := 1.0E‑2;
Double‑Precision
Float double x = 123.4;
Double‑Precision
Float double x = 1e‑2;
Double
Double‑Precision long
double x = 123.4L;
Double
Double‑Precision long
double x = 1e‑2L;
Complex fcomplex
c = {6.2,7.1}; (Create a record)
Arrays float
A[3][2] = {{4,2},{1,‑2},{0,5}};
A(2,2)
:= ‑2;
Enumeration boolean ANS
= NO; TYPE ANS = (NO, YES);
Boolean VAR
BOOLEAN FOUND;
FOUND
:= FALSE;
Pointers char *, ... * ^
Structures struct complex { RECORD1 := RECORD2;
float r = 12.0;
float i = 7.0;
};
File
Pointers FILE
*fptr; OUTFILE :
TEXT;
Ranges I
:= 39;
(1..80
is valid above)
Constants #define PI 3.1415 CONST PI = 3.1415;
const
char DOLLAR = '$'; CONST DOLLAR = '$';
DATA
TYPE CONVERSION:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Character (char) i CHR(ORD(0) + i);
(where
i = 0..9)
String (char
*) x
Integer (int)
ch ORD(ch) ‑
ORD('0');
(where
ch = '0'..'9')
Long
Integer (long)
x
Floating
Point (float)
x (INTEGERs
migrate up
to
REALs)
Double‑Precision
Float (double) x
Double
Double‑Precision (long
double) x
Complex (complex)
x
STANDARD
FUNCTIONS:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Truncation trunc() (in trunc.c) TRUNC()
Round round()
(in round.c) ROUND()
Nearest
Integer ceil()
Nearest
Whole Number floor()
Absolute
Value abs(),
fabs() ABS()
Odd
(INTEGER) #define
ODD(a) (a%2)?(1):(0) ODD()
Square
Root sqrt() SQRT()
Square SQR()
Exponential exp() EXP()
Natural
Log log() LN()
Common
Log log10() (LN()
/ LN(10.0))
Power
of Ten (INTEGER) pow(10.0,x) PWROFTEN(X)
Sine sin() SIN()
Cosine cos() COS()
Tangent tan() (SIN()
/ COS())
Arcsine asin() ATAN(X/SQR(‑X*X+1))
Arccosine acos() ‑ATAN(X/SQR(‑X*X+1))
+ 1.5708
Arctangent atan() ATAN()
Atan of
Quotient atan2()
Hyperbolic
Sine sinh() ((EXP(X)
+ EXP(‑X))
/ 2.0)
Hyperbolic
Cosine cosh() ((EXP(X)
‑ EXP(‑X))
/ 2.0)
Hyperbolic
Tangent tanh() (EXP(X)
‑ EXP(‑X)) /
(EXP(X) + EXP(‑X))
Random
Number rand(),
srand()
SYNTAX:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
Case
Sensitive? YES NO
Name a
program main() PROGRAM
prog_name;
Comment
Begin /* (* ‑or‑ {
Comment
End */ *) ‑or‑ }
Begin
Symbol { BEGIN
End Symbol } END ‑or‑ END.
(last
one only)
Statement
Terminator ; ; ‑or‑ Nothing if
preceding
an END or
ELSE
statement
Include
Files #include
<filename.h> {$I FILENAME.INC}
#include
"filename.h"
Variable
Names a‑zA‑Z0‑9_ A‑Z0‑9
(31 chars max.) (? chars max.)
Functions float func_name (int x,
y)
{
...
return some_float;
}
FUNCTION
FNAME (X,Y: REAL) : REAL;
...
FNAME
:= SOMEREAL;
Procedures proc_name
(int x, y)
PROCEDURE
PROC_NAME (X,Y: REAL);
Get
Input scanf("%f",
&sum); READLN (SUM);
scanf("%c",
&ch); READ (CH);
Print
Output printf("A
= %f\n", A); WRITELN ('A = ',
A);
printf("A
= %f", A); WRITE ('A = ',
A);
printf("\n"); WRITELN;
File
Output #include
<stdio.h>
FILE
*file_id;
file_id
= fopen("filename", "w");
...
fprintf(file_id,
"Any string here\n");
...
fclose(file_id);
VAR
file_id : TEXT;
ASSIGN
(file_id, outfile);
REWRITE
(file_id);
...
WRITELN
(file_id, 'Any string.');
...
CLOSE (file_id);
Exit exit(1);
(Exits main())
Exit
(block name)
CONTROL
STRUCTURES:
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
If‑Then‑Else if
(x>y) IF X
> Y THEN
{ BEGIN
... ...
} END
else
if (x==y) { ELSE IF X = Y
THEN
... ...
}
else { ELSE
... ...
}
While
Loops while
(count != 5) WHILE count <>
5 DO
{ BEGIN
...
...
} END
For
Loops for
(i=1;i<=10;i++) FOR I := 1 TO
10 DO
{ BEGIN
...
...
} END
for
(i=10;i>=1;i‑‑) FOR
I := 10 DOWNTO 1
{ DO
BEGIN
...
...
} END
Case switch
(my_var) { CASE MY_VAR OF
case 'D' : 'D' : BEGIN
... ...
break; END;
case 'Y': case 'y': 'Y', 'y' : ...
... ("break"
not needed)
break;
} END
Repeat do
{ REPEAT
... ...
(No
BEGIN/END needed)
}
while (i < 7); UNTIL (I
< 7);
With No
equivalent (From
RECORD variable
ME.SSAN)
WITH
record_var DO
SSAN :=<PHONE_NUMBER>;
Goto goto
label_text; LABEL 20, 30;
...
label_text : ... GOTO
label_number
(1..9999)
...
label_number : ...
APPENDIX D
Sample Programs in
Other Languages
|
|
Appendix D: Sample
Programs in Other Languages
This appendix is long, but
important. It lists the example
programs of Simpson's Composite Rule for Integration - Algorithm 4.1, in six
different languages! Each of these programs
can be found in the LANGS sub-directory of the distribution diskettes. These files are organized as follows:
LANGS
*
+)))))))))))0)))))))))))0))2))))))))0)))))))))))0))))))))))),
R R R R R R
ADA
BASIC C C++ FORTRAN
PASCAL
R R R R R R
SIMPSON.ADA
SIMPSON.BAS SIMPSON.C SIMPSON.CPP
SIMPSON.FOR SIMPSON.PAS
NAAUTIL.ADA
SIMPSON.IN SIMPSON.H SIMPSON.HPP SIMPSON.IN NAAUTIL.INC
SIMPSON.IN SIMPSON.OUT SIMPSON.IN SIMPSON.IN SIMPSON.OUT NAAMATH.INC
SIMPSON.OUT SIMPSON.OUT SIMPSON.OUT SIMPSON.IN
SIMPSON.OUT
D.1 Ada
D.1.1 SIMPSON.ADA
‑‑
FILE NAME: SIMPSON.ADA
‑‑
LANGUAGE: ADA
‑‑
COMPILER: Meridian Ada 4.1
‑‑
STATUS: Not tested yet
‑‑
****************************************************************************
‑‑
Composite
Simpson's Rule ‑ Algorithm 4.1
‑‑
****************************************************************************
‑‑
‑‑ !b
‑‑
To approximate the integral I = * f(x) dx:
‑‑ "a
‑‑
‑‑
INPUT endpoints a, b; positive integer n; the function f():
‑‑
‑‑
OUTPUT approximation XI to I.
‑‑
‑‑
****************************************************************************
‑‑
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.0 *
‑‑
****************************************************************************
with
naa_util; use naa_util; ‑‑
Numerical Analysis Algorithms utilities
with
math_lib; use math_lib; ‑‑
Contains several useful math functions
with
text_io; use text_io; ‑‑ For file I/O
with
ada_io; use ada_io; ‑‑ For easier text,
integer and float I/O
‑‑
NOTE: ada_io is supplied with the Meridian
‑‑
Ada Compiler
procedure
simpson is
‑‑ *************
‑‑ * constants *
‑‑ *************
‑‑ NOTE: PI is defined in the
package math_lib to 40 decimal places.
outfile
: constant := "simpson.out"; ‑‑ Default name of the output file
eq_text_f : constant := "f(x) =
sin(x)"; ‑‑ Needs
updating $
‑‑ *********
‑‑ * types *
‑‑
*********
type file_type is limited private;
‑‑ *************
‑‑ * variables *
‑‑ *************
a, b, h, x, xi, xi0, xi1, xi2 : float;
n
: positive;
title
: string(1..80);
file_id : file_type;
‑‑ **********************************
‑‑ * LOCAL PROCEDURES AND
FUNCTIONS *
‑‑
**********************************
‑‑
**************************************************************************
‑‑ * f(x) ‑ Function to
evaluate, f(x). Needs updating $. *
‑‑ **************************************************************************
function f(x : in float) return float is
begin
‑‑ f
return (sin(x));
end f;
‑‑
**************************************************************************
‑‑
********
‑‑
* MAIN *
‑‑
********
begin
‑‑ **********
‑‑ * INPUTS *
‑‑ **********
title := get_title; ‑‑ Prompts for optional
comments
put_line ("Composite Simpson's Rule ‑
Algorithm 4.1");
new_line;
put ("Enter endpoint a: ");
get_line (a);
put ("Enter endpoint b: ");
get_line (b);
loop
put ("Enter number of intervals on
[a,b], n: ");
get_line (n);
‑‑ Place an exception handler here for better
use of ADA.
if n <= 0 then ‑‑ ERROR ‑ n can
not be negative.
put_line ("ERROR ‑ n must be
greater than zero.");
end if;
exit when n > 0;
end loop;
‑‑ *************
‑‑ * ALGORITHM *
‑‑ *************
‑‑ STEP #1
h := (b ‑ a)/n;
‑‑ STEP #2
xi0 := f(a) + f(b);
xi1 := 0.0; ‑‑
Summation of f(x(2i‑1))
xi2 := 0.0; ‑‑ Summation of
f(x(2i))
‑‑ STEP #3
for i in 1..n‑1 loop
‑‑ STEP #4
x := a + i*h;
‑‑ STEP #5
if i mod 2 = 0 then
xi2 := xi2 + f(x); ‑‑ For even i
else
xi1 := xi1 + f(x); ‑‑ For odd i
end if;
end loop;
‑‑ STEP #6
xi := h*(xi0 + 2.0*xi2 + 4.0*xi1) / 3.0;
‑‑ ***********
‑‑ * OUTPUTS *
‑‑ ***********
‑‑ STEP #7
‑‑ Write output to the screen.
print_title (title);
put_line ("Composite Simpson`s Rule ‑
Algorithm 4.1");
new_line;
put_line (eq_text_f, " from ", a,
" to ", b, ".");
new_line;
put_line ("n = ", n, "
intervals on [a,b].");
put_line ("Interval number h = ",
h);
new_line;
put_line (" !", b);
put_line ("XI = * f(x) dx = ", xi);
put_line (" "", a);
new_line;
put_line ("Required ", n+1, "
functional evaluations.");
‑‑ Write output to a file.
‑‑ Open outfile for output.
create (file => file_id, mode =>
out_file, name => outfile); ‑‑
See 14.3.10
print_title_to_outfile (file_id, title);
new_line (file_id);
put_line (file_id, "Composite Simpson`s
Rule ‑ Algorithm 4.1");
new_line (file_id);
put_line (file_id, eq_text_f, " from
", a, " to ", b, ".");
new_line (file_id);
put_line (file_id, "n = ", n,
" intervals on [a,b].");
put_line (file_id, "Interval number h =
", h);
new_line (file_id);
put_line (file_id, " !",
b);
put_line (file_id, "XI = * f(x) dx = ", xi);
put_line (file_id, " "",
a);
new_line (file_id);
put_line (file_id, "Required ",
n+1, " functional evaluations.");
close (file => file_id); ‑‑
Closes output file.
new_line;
put_line ("Output saved into file
'", outfile, "'.");
end
simpson; ‑‑
STOP
‑‑
****************************************************************************
‑‑
* Copyright (C) 1991, Harold A. Toomey, All Rights Reserved.
*
‑‑
****************************************************************************
D.1.2 NAAUTIL.ADA
‑‑
****************************************************************************
‑‑
* PACKAGE: NAA_UTIL.ADA *
‑‑
* VERSION: 4.0 *
‑‑
*
*
‑‑
* WRITTEN BY: Harold A. Toomey, CARE‑FREE
SOFTWARE *
‑‑
* DATE: 22 May 1991 (2Q 1991) *
‑‑
*
*
‑‑
* DESCRIPTION: *
‑‑
* Contains useful utilities (functions
and procedures) to be used with *
‑‑
* "Numerical Analysis Algorithms
in Ada" v4.0.
*
‑‑
*
*
‑‑
* VARIABLES: *
‑‑
* numchars : integer;
*
‑‑
*
*
‑‑
* FUNCTIONS: *
‑‑
* get_title() *
‑‑
*
*
‑‑
* PROCEDURES: *
‑‑
* print_title() *
‑‑
* print_title_to_file()
*
‑‑
*
*
‑‑
****************************************************************************
with
ada_io; use ada_io;
‑‑
****************************************************************************
‑‑ Package specification
‑‑
****************************************************************************
package
NAA_UTIL is
numchars : integer; ‑‑ Stores title length in
characters.
function get_title return string;
procedure print_title(
file_id : in file_type;
title
: in string
);
procedure print_title_to_outfile(
file_id : in file_type;
title
: in string
);
end
NAA_UTIL;
‑‑
****************************************************************************
‑‑ Package body
‑‑
****************************************************************************
package
body NAA_UTIL is
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
‑‑
get_title() ‑ Prompts for an optional title.
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
function
get_title return string is
title : string(1..80);
begin ‑‑ get_title
for i in 1..79 loop ‑‑ Print the NAA banner
put ("‑");
end loop;
new_line;
put_line(ht, ht, "'Numerical Analysis
Algorithms in Ada' v4.0");
for i in 1..79 loop
put
("‑");
end loop;
new_line; ‑‑
Get the title
put_line ("Enter a title [ie ‑
Set 2.1, Problem 2 a) ].");
put ("‑‑‑‑>
");
get_line (title);
numchars := title'length; ‑‑ Numchars stores the
length of the title.
return (title);
end get_title;
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
‑‑
print_title() ‑ Prints NAA banner and title to the screen.
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
procedure
print_title (file_id : in file_type, title : in string) is
begin ‑‑ print_title
for i in 1..79 loop ‑‑ Print the NAA banner
put ("‑");
end loop;
new_line;
put_line(ht, ht, "'Numerical Analysis
Algorithms in Ada' v4.0");
for i in 1..79 loop
put ("‑");
end loop;
new_line;
if numchars > 0 then
put_line (title); ‑‑ Print the title
new_line;
end if;
end
print_title;
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
‑‑
print_title_to_outfile() ‑ Prints NAA banner and title to the output
file.
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
procedure
print_title_to_outfile (file_id : in file_type, title : in string) is
begin ‑‑ print_title_to_outfile
for i in 1..79 loop ‑‑ Print the NAA banner
put (file_id, "‑");
end loop;
new_line (file_id);
put_line(file_id, ht, ht, "'Numerical
Analysis Algorithms in Ada' v4.0");
for i in 1..79 loop
put (file_id, "‑");
end loop;
new_line (file_id);
if numchars > 0 then
put_line (file_id, title); ‑‑ Print the title
new_line (file_id);
end if;
end
print_title_to_outfile;
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
end
NAA_UTIL; ‑‑ end
package body NAA_UTIL
‑‑
****************************************************************************
‑‑
* Copyright (C) 1991, Harold A. Toomey, All Rights Reserved.
*
‑‑
****************************************************************************
D.1.3 SIMPSON.IN
NAA v4.0 Sample Output
0.0
3.14159265358979324
20
D.1.4 SIMPSON.OUT
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
'Numerical Analysis Algorithms
in Ada' v4.0
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NAA v4.0 Sample Output
Composite Simpson's Rule ‑
Algorithm 4.1
f(x) = sin(x) from 0 to
3.14159.
n = 20 intervals on [a,b].
Interval number h = 0.15708
!3.14159
XI = * f(x) dx = 2.0000067844
"0
Required 21 functional
evaluations.
D.2 BASIC
D.2.1 SIMPSON.BAS
10 'FILE NAME: SIMPSON.BAS
20 'LANGUAGE:
BASIC
30 'COMPILER:
Microsoft GW‑BASIC Version 3.20
40 'STATUS:
Compiles and runs correctly
50 '
60
'**************************************************************************
70 ' Composite
Simpson's Rule ‑ Algorithm 4.1
80
'**************************************************************************
90 '
100 ' !b
110 ' To approximate the integral I = * f(x) dx:
120 ' "a
130 '
140 ' INPUT endpoints a, b; positive integer n;
the function fnf().
150 '
160 ' OUTPUT approximation XI to I.
170 '
180
'**************************************************************************
190 ' Written by:
Harold A. Toomey, CARE‑FREE SOFTWARE, 2Q 1991, v4.0
200
'**************************************************************************
210 '
220 PI# = 3.141592653589793# 'The constant PI (Usage: X =
2 * PI# )
230 OUTFILE$ = "SIMPSON.OUT" 'Output file name
240 EQTEXTF$ = "f(x) = sin(x)" 'Needs updating $
250 '
260 DEFDBL A, B, H, X 'For XI, XI0, XI1, and XI2 also
270 DEFINT I, N
280 DEFSTR T 'For
title
290 '
300 '**************************************************************************
310 '* FNF(X) ‑
Function to evaluate, f(x). Needs
updating $.
320
'**************************************************************************
330 DEF FNF(X) = SIN(X)
340
'**************************************************************************
350 '
360 '**********
370 '* INPUTS *
380 '**********
390 '
400 'Get the optional title
410 PRINT "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
420 PRINT " 'Numerical Analysis Algorithms in BASIC' v4.0 "
430 PRINT "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
440 PRINT
450 PRINT "Enter a title [ie ‑ Set
2.1, Problem 2 a) ]."
460 INPUT "‑‑‑‑‑>";
TITLE$
470 '
480 PRINT
490 PRINT "Composite Simpson's Rule ‑
Algorithm 4.1"
500 PRINT
510 INPUT "Enter endpoint a = "; A
520 INPUT "Enter endpoint b = "; B
530 INPUT "Enter number of intervals on
[a,b], n = "; N
540 '
550 'ERROR ‑ N must
be positive
560 IF (N <= 0) THEN PRINT "ERROR ‑
n must be greater than zero.": GOTO 530
570 '
580 '*************
590 '* ALGORITHM *
600 '*************
610 '
620 'STEP #1
630 H = (B ‑ A) / N
640 '
650 'STEP #2
660 XI0 = FNF(A) + FNF(B)
670 XI1 = 0! 'Summation
of f(x(2i‑1))
680 XI2 = 0! 'Summation
of f(x(2i))
690 '
700 'STEP #3
710 FOR
I = 1 TO N ‑ 1
720 '
730 ' STEP #4
740 X = A + I*H
750 '
760 ' STEP #5 (For even i) (For odd i)
770 IF (I MOD 2 = 0) THEN XI2 = XI2 + FNF(X)
ELSE XI1 = XI1 + FNF(X)
780 '
790 NEXT I
800 '
810 'STEP #6
820 XI = H * (XI0 + 2*XI2 + 4*XI1) / 3
830 '
840 '***********
850 '* OUTPUTS *
860 '***********
870 '
880 'STEP #7
890 'Write output to the
SCREEN
900 PRINT "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
910 PRINT " 'Numerical Analysis Algorithms in BASIC' v4.0 "
920 PRINT "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
930 PRINT
940 PRINT TITLE$ 'Print
optional title
950 PRINT
960 PRINT "Composite Simpson's Rule ‑
Algorithm 4.1"
970 PRINT
980 PRINT EQTEXTF$, " from"; A
;"to"; B ;"."
990 PRINT
1000 PRINT "n ="; N ;"intervals on
[a,b]."
1010 PRINT "Interval number h ="; H
1020 PRINT
1030 PRINT " !"; B
1040 PRINT "XI = * f(x) dx = "; XI
1050 PRINT " ""; A
1060 PRINT
1070 PRINT "Required"; N+1
;"functional evaluations."
1080 '
1090 'Write output to a
FILE
1100 OPEN "O", #1, OUTFILE$ 'Create or open the file "041.OUT"
1110 PRINT#1, "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
1120 PRINT#1, " 'Numerical Analysis Algorithms in BASIC' v4.0 "
1130 PRINT#1, "‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑"
1140 PRINT#1,
1150 PRINT#1, TITLE$ 'Print optional title
1160 PRINT#1,
1170 PRINT#1, "Composite Simpson's Rule ‑
Algorithm 4.1"
1180 PRINT#1,
1190 PRINT#1, EQTEXTF$, " from"; A
;"to"; B ;"."
1200 PRINT#1,
1210 PRINT#1, "n ="; N ;"intervals
on [a,b]."
1220 PRINT#1, "Interval number h ="; H
1230 PRINT#1,
1240 PRINT#1, " !"; B
1250 PRINT#1, "XI = * f(x) dx = "; XI
1260 PRINT#1, " ""; A
1270 PRINT#1,
1280 PRINT#1, "Required"; N + 1
;"functional evaluations."
1290 CLOSE #1
1300 '
1310 PRINT
1320 PRINT "Output saved into file '";
OUTFILE$; "'."
1330 END 'STOP
1340 '
1350 '************************************************************************
1360 ' Copyright (C) 1991, Harold A. Toomey, All
Rights Reserved.
1370
'*************************************************************************
D.2.2 SIMPSON.IN
NAA v4.0 Sample Output
0.0
3.14159265358979324
20
D.2.3 SIMPSON.OUT
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
'Numerical Analysis Algorithms in BASIC' v4.0
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NAA 4.0 Sample Output
Composite Simpson's Rule ‑
Algorithm 4.1
f(x) = sin(x) from 0 to 3.14159265358979 .
n = 20 intervals on [a,b].
Interval number h =
.1570796326794895
! 3.14159265358979
XI = * f(x) dx = 2.000006886810941
" 0
Required 21 functional
evaluations.
D.3 C
D.3.1 SIMPSON.C
/*
** FILE NAME: SIMPSON.C
** LANGUAGE:
C
** COMPILERS: Any ANSI C Compiler (Microsoft C 5.0, Turbo C 2.0, etc.)
** STATUS:
Compiles and runs correctly
*/
/******************************************************************************
Composite
Simpson's Rule ‑ Algorithm 4.1
*******************************************************************************
!b
To
approximate the integral I = * f(x) dx:
"a
INPUT
endpoints a, b; positive integer n; the function f().
OUTPUT
approximation XI to I.
*******************************************************************************
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.0 *
******************************************************************************/
#include
"naautil.h" /*
Numerical Analysis Algorithms Utilities. */
#define PI 3.141592653589793238462643383279502884197
char
*outfile = "simpson.out"; /* Default name of the output file. */
char
*eq_text_f = "f(x) = sin(x)"; /*
Needs updating $. */
/*****************************************************************************/
/* f(x) ‑
Function to evaluate, f(x). Needs
updating $. */
/*****************************************************************************/
double
f(x)
double x;
{
return (sin(x));
}
/*****************************************************************************/
main()
{
double a, b, h, X, XI, XI0, XI1, XI2, f();
int i, n;
/**********
* INPUTS *
**********/
get_title(); /*
Prompts for optional comments. */
printf("Composite Simpson's Rule ‑
Algorithm 4.1\n\n");
printf("%s\n\n", eq_text_f);
printf("Enter endpoint a: ");
scanf("%lf", &a);
printf("Enter endpoint b: ");
scanf("%lf", &b);
do {
printf("Enter number of intervals on
[a,b], n: ");
scanf("%d", &n);
if (n <= 0)
printf("ERROR ‑ n must be
greater than zero.\n");
} while (n <= 0);
/*************
* ALGORITHM *
*************/
/* STEP #1 */
h = (b ‑ a)/n;
/* STEP #2 */
XI0 = f(a) + f(b);
XI1 = 0.0; /*
Summation of f(x(2i‑1)). */
XI2 = 0.0; /*
Summation of f(x(2i)). */
/* STEP #3 */
for (i=1;i<n;i++) {
/* STEP #4 */
X = a + i*h;
/* STEP #5 */
if (i % 2 == 0)
XI2 += f(X); /* For even i. */
else
XI1 += f(X); /* For odd i. */
}
/* STEP #6 */
XI = h*(XI0 + 2.0*XI2 + 4.0*XI1) / 3.0;
/***********
* OUTPUTS *
***********/
/* STEP #7 */
/* Write output to the screen. */
printf("Interval number h =
%lg\n\n", h);
printf(" !%lg\n", b);
printf("XI = * f(x) dx = %.11lg\n", XI);
printf(" "%lg\n\n", a);
printf("Required %d functional
evaluations.\n", n + 1);
/* Write output to a file. */
open_outfile(outfile);
fprintf(file_id, "Composite Simpson's
Rule ‑ Algorithm 4.1\n\n");
fprintf(file_id, "%s from %lg to
%lg.\n\n", eq_text_f, a, b);
fprintf(file_id, "n = %d intervals on
[a,b].\n", n);
fprintf(file_id, "Interval number h =
%lg\n\n", h);
fprintf(file_id, " !%lg\n",
b);
fprintf(file_id, "XI = * f(x) dx = %.11lg\n", XI);
fprintf(file_id, " "%lg\n\n",
a);
fprintf(file_id, "Required %d
functional evaluations.\n", n + 1);
close_outfile(outfile);
printf("\nOutput saved into file
\"%s\".\n", outfile);
} /*
STOP */
/*****************************************************************************/
/* Copyright (C) 1991, Harold A. Toomey, All Rights Reserved. */
/*****************************************************************************/
D.3.2 NAAUTIL.H
/*******************************
NAAUTIL.H ************************************
"Numerical Analysis Algorithms in C" Utilities I
v4.0
******************************************************************************/
/*
** Return
Procedure
** Value
Name Description
** ‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
** void naaerror ‑ Exits a program with an error message
** void get_title ‑ Prompts for an optional title
** void open_outfile ‑ Opens the default output file
** void close_outfile ‑
Closes the default output file
*/
/***********/
/*
DEFINES */
/***********/
/*
** The ANSI FLAG below allows the user more
flexibility when compiling and
** running these Numerical Analysis
Algorithms. Set to TRUE first. Older
** C compilers may require it to be set to
FALSE. No adverse effects should
** occur.
*/
#ifndef
TRUE
#define
TRUE 1 /* Define TRUE if not already
defined. */
#endif
#ifndef
FALSE
#define
FALSE 0 /* Define FALSE if not already
defined. */
#endif
#define ANSI TRUE /* Set to TRUE if using an ANSI C
standard */
/*
compliant compiler (default).
*/
/*
Set to FALSE if using an older C compiler.*/
/*
ANSI = American National Standards
*/
/* Institute */
/*****************
* INCLUDE FILES *
*****************/
#include
<math.h> /*
For math function prototypes.
*/
#include
<stdio.h> /*
For scanf(), printf() and fprintf().
*/
#if ANSI
== TRUE
#include
<stdlib.h> /*
Needed for calloc() by some compilers and */
#endif /*
for tolower().
*/
/********************
* GLOBAL VARIABLES *
********************/
char
title[133]; /*
Used in get_title() and print_title().
*/
FILE
*file_id; /*
Stream used to save output into a file.
*/
/***********************
* FUNCTION PROTOTYPES *
***********************/
#if ANSI
== TRUE
/* ANSI STANDARD PROTOTYPING (Post‑December
14, 1989) */
void
naaerror (char []);
void
get_title (void);
void
open_outfile (char *);
void
close_outfile (char *);
#else
/* OLDER STYLE PROTOTYPING (Pre‑December
14, 1989) */
/* Placed here for compatibility with older
C compilers. */
void
naaerror();
void
get_title();
void
open_outfile();
void
close_outfile();
#endif
/***************
* SUBROUTINES *
***************/
/*****************************************************************************/
/*
naaerror() ‑ Numerical Analysis Algorithms standard error handler. */
/*****************************************************************************/
void
naaerror(error_text)
char
error_text[];
{
fprintf(stderr,"\nNumerical Analysis
Algorithms run‑time error...\n");
fprintf(stderr,"%s", error_text);
fprintf(stderr,"\n...now exiting to
system...\n");
exit (1);
}
/*****************************************************************************/
/*
get_title() ‑ Prints the NAA banner and prompts for an optional
title. */
/*****************************************************************************/
void
get_title()
{
int i;
/* Print the Numerical Analysis Algorithms
banner. */
for (i=1;i<80;i++) printf("‑");
printf("\n\t\t\"Numerical Analysis
Algorithms in C\" v4.0\n");
for (i=1;i<80;i++) printf("‑");
printf("\n");
printf("Enter a title [ie ‑ Set
2.1, Problem 2 a) ].\n‑‑‑‑>
");
fgets(title, 133, stdin);
printf("\n");
}
/*****************************************************************************/
/*
open_outfile() ‑ Opens the default output file and prints the NAA
banner */
/* and optional title. */
/*****************************************************************************/
void
open_outfile(outfile)
char
*outfile;
{
char msg[80]; /* Holds an error
message string */
int i;
/* Open the default output file. */
if ((file_id = fopen(outfile,
"w")) == NULL) {
sprintf(msg, "Can not open the output
file named \"%s\".", outfile);
naaerror(msg);
}
/* Print the Numerical Analysis Algorithms
banner. */
for (i=1;i<80;i++) fprintf(file_id, "‑");
fprintf(file_id,
"\n\t\t\"Numerical Analysis Algorithms in C\" v4.0\n");
for (i=1;i<80;i++) fprintf(file_id, "‑");
fprintf(file_id, "\n\n");
/* Print the optional title. */
if (title[0] != '\n')
fprintf(file_id, "%s\n", title);
}
/*****************************************************************************/
/*
close_outfile() ‑ Closes the default output file. */
/*****************************************************************************/
void
close_outfile(outfile)
char
*outfile;
{
char msg[80]; /* Holds an error
message string */
if (fclose(file_id) == EOF) {
sprintf(msg, "Can not close the
output file named \"%s\".", outfile);
naaerror(msg);
}
}
/*****************************************************************************/
/* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE, 2Q
1991, v4.0 */
/* Copyright (C) 1991, Harold A.
Toomey, All Rights Reserved.
*/
/*****************************************************************************/
D.3.3 SIMPSON.IN
NAA v4.0 Sample Output
0.0
3.14159265358979324
20
D.3.4 SIMPSON.OUT
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
"Numerical Analysis
Algorithms in C" v4.0
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NAA v4.0 Sample Output
Composite Simpson's Rule ‑
Algorithm 4.1
f(x) = sin(x) from 0 to
3.14159.
n = 20 intervals on [a,b].
Interval number h = 0.15708
!3.14159
XI = * f(x) dx = 2.0000067844
"0
Required 21 functional
evaluations.
D.4 C++
D.4.1 SIMPSON.CPP
//
// FILE NAME: SIMPSON.CPP
// LANGUAGE:
C++
// COMPILERS: Borland C++ or Turbo C++ 2.0
// STATUS:
Not tested yet
//
/******************************************************************************
Composite
Simpson's Rule ‑ Algorithm 4.1
*******************************************************************************
!b
To
approximate the integral I = * f(x) dx:
"a
INPUT
endpoints a, b; positive integer n; the function f().
OUTPUT
approximation XI to I.
*******************************************************************************
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.2 *
******************************************************************************/
#include
"simpson.hpp" //
Numerical Analysis Algorithms Utilities.
//
Also contains #include <iostream.h>.
#define PI 3.141592653589793238462643383279502884197
char
*outfile = "simpson.out"; // Default name of the output file.
char
*eq_text_f = "f(x) = sin(x)"; //
Needs updating $.
/***********************/
/*
FUNCTION PROTOTYPES */
/***********************/
double
f(double x);
/*****************************************************************************/
/* f(x) ‑
Function to evaluate, f(x). Needs
updating $. */
/*****************************************************************************/
double
f(double x)
{
return (sin(x));
}
/*****************************************************************************/
void
main(void)
{
double a, b, h, X, XI, XI0, XI1, XI2, f();
int i, n;
/**********
* INPUTS *
**********/
get_title(); //
Prompts for optional comments.
cout << "Composite Simpson's Rule
‑ Algorithm 4.1\n\n";
cout << eq_text_f <<
"\n\n";
cout << "Enter endpoint a:
";
cin >> a;
cout << "Enter endpoint b:
";
cin >> b;
do {
cout << "Enter number of
intervals on [a,b], n: ";
cin >> n;
if (n <= 0)
cerr << "ERROR ‑ n must
be greater than zero.\n";
} while (n <= 0);
/*************
* ALGORITHM *
*************/
/* STEP #1 */
h = (b ‑ a)/n;
/* STEP #2 */
XI0 = f(a) + f(b);
XI1 = 0.0; //
Summation of f(x(2i‑1)).
XI2 = 0.0; //
Summation of f(x(2i)).
/* STEP #3 */
for (i=1;i<n;i++) {
/* STEP #4 */
X = a + i*h;
/* STEP #5 */
if (i % 2 == 0)
XI2 += f(X); // For even i.
else
XI1 += f(X); // For odd i.
}
/* STEP #6 */
XI = h*(XI0 + 2.0*XI2 + 4.0*XI1) / 3.0;
/***********
* OUTPUTS *
***********/
/* STEP #7 */
// Write output to the screen.
cout << "Interval number h =
" << h << "\n\n";
cout << " !"
<< b << "\n";
cout << "XI = * f(x) dx = " << XI <<
"\n";
cout << " ""
<< a << "\n\n";
cout << "Required " <<
n + 1 << " functional evaluations.\n";
// Write output to a file.
open_outfile(outfile);
fprintf(file_id, "Composite Simpson's
Rule ‑ Algorithm 4.1\n\n");
fprintf(file_id, "%s from %lg to
%lg.\n\n", eq_text_f, a, b);
fprintf(file_id, "n = %d intervals on
[a,b].\n", n);
fprintf(file_id, "Interval number h =
%lg\n\n", h);
fprintf(file_id, " !%lg\n",
b);
fprintf(file_id, "XI = * f(x) dx = %.11lg\n", XI);
fprintf(file_id, " "%lg\n\n",
a);
fprintf(file_id, "Required %d
functional evaluations.\n", n + 1);
close_outfile(outfile);
cout << "\nOutput saved into file
\"" << outfile << "\".\n";
} //
STOP
/*****************************************************************************/
/* Copyright (C) 1991, Harold A.
Toomey, All Rights Reserved.
*/
/*****************************************************************************/
D.4.2 NAAUTIL.HPP
/******************************
NAAUTIL.HPP ***********************************
"Numerical Analysis Algorithms in C++" Utilities I
v4.0
******************************************************************************/
//
// Return
Procedure
// Value
Name Description
// ‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
// void naaerror ‑ Exits a program with an error message
// void get_title ‑ Prompts for an optional title
// void open_outfile ‑ Opens the default output file
// void close_outfile ‑
Closes the default output file
//
/*****************
* INCLUDE FILES *
*****************/
#include
<stdio.h> //
For fprintf().
#include
<iostream.h> //
For cin, cout and cerr.
#include
<stdlib.h> //
Needed for calloc() by some compilers and
//
for tolower().
#include
<math.h> //
For math function prototypes.
/********************
* GLOBAL VARIABLES *
********************/
char
title[133]; //
Used in get_title() and print_title().
FILE
*file_id; //
Stream used to save output into a file.
/***********************
* FUNCTION PROTOTYPES *
***********************/
void
naaerror (char []);
void
get_title (void);
void
open_outfile (char *);
void
close_outfile (char *);
/***************
* SUBROUTINES *
***************/
/*****************************************************************************/
/*
naaerror() ‑ Numerical Analysis Algorithms standard error handler. */
/*****************************************************************************/
void
naaerror(char error_text[])
{
cerr << "\nNumerical Analysis
Algorithms run‑time error...\n";
cerr << error_text;
cerr << "\n...now exiting to
system...\n";
exit (1);
}
/*****************************************************************************/
/*
get_title() ‑ Prints the NAA banner and prompts for an optional
title. */
/*****************************************************************************/
void get_title(void)
{
int i;
// Print the Numerical Analysis Algorithms
banner.
for (i=1;i<80;i++) cout << "‑";
cout << "\n\t\t\"Numerical
Analysis Algorithms in C++\" v4.0\n";
for (i=1;i<80;i++) cout << "‑";
cout << "\n";
cout << "Enter an optional title
[ie ‑ Set 2.1, Problem 2 a) ].\n‑‑‑‑>
";
fgets(title, 133, stdin);
cout << "\n";
}
/*****************************************************************************/
/*
open_outfile() ‑ Opens the default output file and prints the NAA
banner */
/* and optional title. */
/*****************************************************************************/
void
open_outfile(char *outfile)
{
char msg[80]; // Holds an error
message string.
int i;
// Open the default output file.
if ((file_id = fopen(outfile,
"w")) == NULL) {
sprintf(msg, "Can not open the output
file named \"%s\".", outfile);
naaerror(msg);
}
// Print the Numerical Analysis Algorithms
banner.
for (i=1;i<80;i++) fprintf(file_id, "‑");
fprintf(file_id,
"\n\t\t\"Numerical Analysis Algorithms in C++\" v4.0\n");
for (i=1;i<80;i++) fprintf(file_id, "‑");
fprintf(file_id, "\n\n");
// Print the optional title.
if (title[0] != '\n')
fprintf(file_id, "%s\n", title);
}
/*****************************************************************************/
/*
close_outfile() ‑ Closes the default output file. */
/*****************************************************************************/
void
close_outfile(char *outfile)
{
char msg[80]; // Holds an error
message string.
if (fclose(file_id) == EOF) {
sprintf(msg, "Can not close the
output file named \"%s\".", outfile);
naaerror(msg);
}
}
/*****************************************************************************/
/* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.0 */
/* Copyright (C) 1991, Harold A.
Toomey, All Rights Reserved.
*/
/*****************************************************************************/
D.4.3 SIMPSON.IN
NAA v4.2 Sample Output
0.0
3.14159265358979324
20
D.4.4 SIMPSON.OUT
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
"Numerical Analysis
Algorithms in C++" v4.0
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NAA v4.0 Sample Output
Composite Simpson's Rule ‑
Algorithm 4.1
f(x) = sin(x) from 0 to
3.14159.
n = 2m = 20 subintervals of
[a,b].
Interval number h = 0.15708
!3.14159
XI = * f(x) dx = 2.0000067844
"0
Required 21 functional
evaluations.
D.5 FORTRAN 77
D.5.1 SIMPSON.FOR
C FILE NAME: SIMPSON.FOR
C LANGUAGE:
FORTRAN 77
C COMPILER:
Microsoft FORTRAN 77 Version 3.3
C STATUS:
Compiles and runs correctly
C
C
*****************************************************************************
C Composite Simpson's Rule ‑ Algorithm
4.1
C
*****************************************************************************
C
C !b
C To
approximate the integral I = * f(x) dx:
C "a
C
C INPUT
endpoints a, b; positive integer n; the function f().
C
C OUTPUT
approximation XI to I.
C
C
*****************************************************************************
C Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.0
C
*****************************************************************************
C
C
PROGRAM SIMPSON
C
DOUBLE PRECISION A, B, H, X
INTEGER OUT, I, N
CHARACTER*80 TITLE
CHARACTER*12 OUTFILE
C
C ‑‑ OUT will be assigned to
OUTFILE for printing to an output file
PARAMETER (OUT=4)
C
C ‑‑ Default name of the
outfile
DATA OUTFILE/'SIMPSON.OUT'/
C
C
*****************************************************************************
C * F(X) ‑
Function to evaluate, f(x). Needs
updating $.
C
*****************************************************************************
C
F(X) = DSIN(X)
C
C
*****************************************************************************
C
C **********
C * INPUTS *
C **********
C
C ‑‑ Prompts for optional title
WRITE (*,1)
WRITE (*,2)
WRITE (*,3)
WRITE (*,*) ' Enter a title [ie ‑
Set 2.1, Problem 2 a) ].'
WRITE (*,*) ' ‑‑‑‑>
'
READ (*, 100) TITLE
100 FORMAT(A80)
WRITE (*,4)
WRITE (*,*) 'Enter endpoint a:'
READ (*, 101) A
101 FORMAT(D8.0)
WRITE (*,*) 'Enter endpoint b:'
READ (*, 102) B
102 FORMAT(D8.0)
200 WRITE (*,*) 'Enter number of intervals on
[a,b], n:'
READ (*, 103) N
103 FORMAT(I8)
C
C ‑‑ ERROR ‑ n must be
positive
IF (N .LE. 0) THEN
WRITE (*,*) 'ERROR ‑ n must be
greater than zero.'
GOTO 200
ENDIF
C
C *************
C * ALGORITHM *
C *************
C
C STEP #1
H = (B ‑ A) / N
C
C STEP #2
XI0 = F(A) + F(B)
C ‑‑ Summation of f(x(2i‑1))
XI1 = 0.0
C ‑‑ Summation of f(x(2i))
XI2 = 0.0
C
C STEP #3
DO 50 I=1,N‑1
C
C STEP #4
X = A + I*H
C
C STEP #5
IF (MOD(I,2) .EQ. 0) THEN
C ‑‑ For I even
XI2 = XI2 + F(X)
ELSE
C ‑‑ For I odd
XI1 = XI1 + F(X)
ENDIF
50 CONTINUE
C
C STEP #6
XI = H * (XI0 + 2*XI2 + 4*XI1) / 3.0
C
C ***********
C * OUTPUTS *
C ***********
C
C STEP #7
C ‑‑ Write output to the screen
(*) and to a file (OUT=4).
C ‑‑ Open outfile for output
C OPEN (OUT,FILE=OUTFILE,STATUS='UNKNOWN')
OPEN (OUT,FILE=OUTFILE)
C
WRITE (*,1)
WRITE (OUT,1)
WRITE (*,2)
WRITE (OUT,2)
WRITE (*,3)
WRITE (OUT,3)
1 FORMAT(' ',78('‑'))
2 FORMAT(' ',16X,'"Numerical Analysis
Algorithms in FORTRAN" v4.0')
3 FORMAT(' ',78('‑'),/)
WRITE (*,*) TITLE
WRITE (OUT,*) TITLE
WRITE (*,4)
WRITE (OUT,4)
4 FORMAT(' Composite Simpson`s Rule ‑
Algorithm 4.1',/)
WRITE (*,5) A, B
WRITE (OUT,5) A, B
5 FORMAT(' f(x) = sin(x) from ',D12.7,' to
',D12.7,'.',/) A, B
WRITE (*,6) N
WRITE (OUT,6) N
6 FORMAT(' n = ',I4,' intervals on [a,b].')
WRITE (*,7) H
WRITE (OUT,7) H
7 FORMAT(' Interval number h = ',D13.7/)
WRITE (*,8) B
WRITE (OUT,8) B
8 FORMAT(' !',D13.7)
WRITE (*,9) XI
WRITE (OUT,9) XI
9 FORMAT(' I = * f(x) dx = ',D13.7)
WRITE (*,10) A
WRITE (OUT,10) A
10 FORMAT(' "',D13.7/)
WRITE (*,11) N + 1
WRITE (OUT,11) N + 1
11 FORMAT(' Required ',I4,' functional
evaluations.',/)
C
C ‑‑ Closes outfile previously
opened for output
ENDFILE (OUT)
CLOSE (OUT)
WRITE (*,12) OUTFILE
12 FORMAT(' Output saved into file "',
A, '".',/)
C
END
C
C
*****************************************************************************
C Copyright (C) 1991, Harold A. Toomey, All Rights Reserved.
C
*****************************************************************************
D.5.2 SIMPSON.IN
NAA v4.0 Sample Output
0.0
3.14159265358979324
20
D.5.3 SIMPSON.OUT
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
"Numerical Analysis Algorithms in
FORTRAN" v4.0
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
NAA 4.2 Sample Output
Composite Simpson`s Rule ‑ Algorithm 4.1
f(x) = sin(x) from .0000000D+00 to .3141592D+01.
n = 20 intervals on [a,b].
Interval number h =
.1570796D+00
! .3141592D+01
I = * f(x) dx = .2000007D+01
" .0000000D+00
Required 21 functional
evaluations.
D.6 Pascal
D.6.1 SIMPSON.PAS
{
FILE
NAME: SIMPSON.PAS
LANGUAGE: PASCAL
COMPILER: Turbo PASCAL Version 3.02A
STATUS: Compiles and runs correctly
Note: NAAMATH.INC has not been
fully tested yet
}
{******************************************************************************
Composite
Simpson's Rule ‑ Algorithm 4.1
*******************************************************************************
!b
To
approximate the integral I = * f(x) dx:
"a
INPUT
endpoints a, b; positive integer n; the function f().
OUTPUT
approximation XI to I.
*******************************************************************************
* Written by: Harold A. Toomey, CARE‑FREE SOFTWARE,
2Q 1991, v4.0 *
******************************************************************************}
PROGRAM
simpson;
{ USES
TRANSCEND } {
Un‑comment if using UCSD Pascal. }
TYPE
STRING_TYPE = STRING[80];
CONST
PI =
3.1415926535897932384626433832795028841972;
outfile = 'simpson.out'; { Default name of the output file.
}
eq_text_f = 'f(x) = sin(x)';{ Needs
Updating $ }
VAR
a, b, h, X, XI, XI0, XI1, XI2 : REAL;
i, n
: INTEGER;
title
: STRING_TYPE;
file_id : TEXT;
{****************************
* PROCEDURES AND FUNCTIONS *
****************************}
{$I NAAUTIL.INC} { Numerical Analysis Algorithms Utilities.
}
{$I NAAMATH.INC} { Complete set of math functions. }
{*****************************************************************************
* f(x) ‑ Function to evaluate,
f(x). Needs updating $. *