Numerical Computation in C

Numerical Computation in C
Computer Programmin in C
Fall Semester 2012-2013
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
C Programming by Ali
iskurt
Numerical Computation
in C
1
Reminder – Reading Assignment in
Kernighan & Ritchie
• Chapter 1 — Introduction
• §1.1 – Getting Started
• §1.2 – Variables and Arithmetic Expressions
• Chapter 2 — Types, Operators, and
Expressions
C Programming by Ali
iskurt
Numerical Computation
in C
2
Reminder – Programming Assignment #1
• Due Thursday, October 11, at 15:00
• Problem:–
• Read in the x- and y-coordinates of the three corners
of a triangle
• Compute and print out the circumference and area of
that triangle
• Need to know:–
• Reading assignment
• printf() and scanf()
– See pp. 154 & 158 and/or Appendix B1.2 and B1.3
• sqrt() – square root function
C Programming by Ali
iskurt
Numerical Computation
in C
3
Review:– C is a “typed” language
• I.e., every data item has a “type” associated
with it
• E.g., integer, floating point, character, structure,
array, …
• Several purposes
• So compiler knows how to handle it in programs
• So compiler knows how to convert from one type to
another
• So you don’t have to keep track of this crucial detail
•…
C Programming by Ali
iskurt
Numerical Computation
in C
4
Review:– Numerical Data Types
• int – a signed integer, usually 16 or 32 bits
• long – a signed integer, usually 32 or 64 bits
• short – a signed integer, usually 16 bits
• Sizes of int, long, and short are machine dependent
• float – a real number in exponent-mantissa
form, usually 32 bits in length
• double – a real number in exponent-mantissa
form, usually 64 bits in length
• float and double are almost always IEEE standard format
C Programming by Ali
iskurt
Numerical Computation
in C
5
Review:– Integer Data Types
• Integer types may be unsigned or signed
– E.g.,
• int i;
/* signed */
• long j;
/* signed */
• unsigned short k;
– Default is signed
• Value ranges
– signed: –2(n-1) … +2(n-1)-1
– unsigned: 0 … +2(n)-1
C Programming by Ali
iskurt
Numerical Computation
in C
6
Floating Point Data Types
• A way of representing numbers with very
large or small magnitudes in computers
• … with a high degree of precision
• Equivalent to scientific notation
• … but in binary
• Examples
• 3.14159265358979323846 — 
• 2.99792458  108 m/s — c, the velocity of light
• 6.626 068 85  10-27 erg sec — h, Planck’s constant
C Programming by Ali
iskurt
Numerical Computation
in C
7
Digression:– an Engineering Mystery
• It is known from their own writings that the
ancient Egyptians …
• … knew the value of  to be “about 3”
• … did not have the mathematical sophistication to
compute it to any decimal places of precision
• So in building the Great Pyramid, how did
they make the ratio of the lengths of its
sides to its height be an integer multiple of
 — accurate to one part in 1000?
C Programming by Ali
iskurt
Numerical Computation
in C
8
Floating Point Representation
S
exponent
mantissa
• S = sign bit
• 0 = positive, 1 = negative
• Exponent
• Binary power of 2 to which number is raised
• Mantissa
• Binary representation of fractional part
• (Usually) in range 1.0 ≤ m  2.0
C Programming by Ali
iskurt
Numerical Computation
in C
9
Floating Point Representation (continued)
• float f;
• 1 sign bit
• 8 exponent bits
• 23 mantissa bits
• double g;
• 1 sign bit
• 11 exponent bits
• 52 mantissa bits
There is also a long double
type – 128 bits total.
It is unlikely that you will ever have
to convert from binary to decimal or
vice versa “by hand”— printf() and
scanf() will do it for you.
• Value of floating point number
• 1.m0m1m2…m22  2(exp-127)
• 1.m0m1m2……m51  2(exp-1023)
C Programming by Ali
iskurt
Numerical Computation
in C
// float
// double
10
Simple Program Example
• Calculate the lengths of the sides of a regular
polygon, given …
– the number of sides, and
– the radius of the circumscribing circle
C Programming by Ali
iskurt
Numerical Computation
in C
11
Simple Program Example (continued)
#include <stdio.h>
#include <math.h>
const double pi =
3.14159265358979323846;
int main () {
unsigned int n;
double r, length;
printf(″Enter # of ″
″sides:- ″);
scanf(″%u″, &n);
printf(″Enter radius″
″:- ″);
C Programming by Ali
iskurt
scanf(″%lf″, &r);
/* calculate length */
length = 2 * r *
sin(pi/n);
printf(″The length of ″
″a side of an %u-″
″sided polygon of ″
″radius %f is %f.″
″\n″, length);
return 0;
} // main
Numerical Computation
in C
12
Digression:– Coding Conventions
• Definition:– White Space
– A blank, tab, new line, vertical tab, form feed,
or comment
• White space is ignored
– However, it separates adjacent identifiers,
keywords, constants, operators, etc.
• E.g. long double, unsigned int
C Programming by Ali
iskurt
Numerical Computation
in C
13
Digression:– Coding Conventions (cont.)
• String constants (i.e., in double quotes) may
not span lines!
– E.g., "We, the people of the United
States, in order to form …"
• Adjacent string constants (in double quotes)
are concatenated!
– E.g., "We, the people of the United"
" States, in order to form …"
C Programming by Ali
iskurt
Numerical Computation
in C
14
Digression:– Coding Conventions (cont.)
•
Comments
1. Any sequence of characters between "/*" and "*/"
2. Any sequence of characters between "//" and end of
line
–
… but not in a string constant (i.e., between double quotes)
•
Comments are equivalent to white space
•
Comments are necessary to create readable code
C Programming by Ali
iskurt
Numerical Computation
in C
15
Simple Program Example (continued)
#include <stdio.h>
#include <math.h>
const double pi =
3.14159265358979323846;
int main () {
unsigned int n;
double r, length;
printf(″Enter # of ″
″sides:- ″);
scanf(″%u″, &n);
printf(″Enter radius″
″:- ″);
C Programming by Ali
iskurt
scanf(″%lf″, &r);
/* calculate length */
length = 2 * r *
sin(pi/n);
printf(″The length of ″
″a side of an %u-″
″sided polygon of ″
″radius %f is %f.″
″\n″, n, r,
length);
return 0;
} // main
Numerical Computation
in C
16
Summary – Simple Example
• Printing
• Simple (concatenated) strings
• Strings with embedded data
• Scanning
• Unsigned integers
• Doubles (i.e., 64-bit floating point numbers)
• Assignment
• Value to length
• Function call
• sin
• Constant definition
• pi
C Programming by Ali
iskurt
Numerical Computation
in C
17
Declaration vs. Definition
• Definition:– Declare – Introduce an identifier and
associate it with a type
• No storage is created
• Nothing is compiled; compiler merely records information in
its symbol table
• Definition:– Define – Create or set aside the code
or storage for the object named by the identifier
• Storage is created and/or code is compiled
• Body of function is “filled in”
C Programming by Ali
iskurt
Numerical Computation
in C
18
Definitions of Numeric Data
unsigned int i;
int j, k;
short m = 0;
long n = m;
• Allocate a memory
location big enough to
hold an unsigned
integer.
• Name of that location
is i
…
C Programming by Ali
iskurt
Numerical Computation
in C
19
Definitions of Numeric Data
unsigned int i;
int j, k;
• Allocate two memory
locations big enough
to hold an integer.
short m = 0;
long n = m;
…
C Programming by Ali
iskurt
• Names of those
locations are j and k
• Cannot count on them
being in contiguous
locations
Numerical Computation
in C
20
Definitions of Numeric Data
unsigned int i;
int j, k;
short m = 0;
• Allocate a memory location
big enough to hold a short
integer.
– i.e., short int m = 0
• Name of that location is m
long n = m;
…
C Programming by Ali
iskurt
• Initialize the value of that
location to 0
Numerical Computation
in C
21
Definitions of Numeric Data
unsigned int i;
int j, k;
short m = 0;
long n = m;
…
C Programming by Ali
iskurt
• Allocate a memory
location big enough to
hold a long integer.
• Name of that location
is n
• Initialize the value of
that location to the
value stored in m
Numerical Computation
in C
22
Definitions of Numeric Data
unsigned int i;
int j, k;
short m = 0;
• What if we had tried to
initialize it to k instead?
• What would value of n
be?
long n = k;
…
C Programming by Ali
iskurt
Numerical Computation
in C
23
Definitions of Numeric Data (continued)
double a;
• Same as previous, but
for floating point data
float b = 3.5;
float d = 9.3e6;
double e = 2.1e-8;
…
C Programming by Ali
iskurt
Numerical Computation
in C
24
Definitions of Numeric Data (continued)
double a;
• Same as previous, but
for floating point data
float b = 3.5;
float d = 9.3e6;
double e = 2.1e-8;
• Note the decimalized
notation for the
initialization
…
C Programming by Ali
iskurt
Numerical Computation
in C
25
Definitions of Numeric Data (continued)
double a;
• Same as previous, but
for floating point data
float b = 3.5;
• Scientific notation for
initializations – i.e.,
float d = 9.3e6;
double e = 2.1e-8;
…
C Programming by Ali
iskurt
– 9.3  106
– 2.1  10-8
Numerical Computation
in C
26
Questions?
C Programming by Ali
iskurt
Numerical Computation
in C
27
Assignment Operator
• location ‘=’ value
– Assigns the value from the right side to the
memory location defined by the left
• E.g.,
–i = 3
–j = i
– f = sin(x)
Note: computer scientists often refer
to the location as the l-value (i.e.,
left value; see p.197)
– g = expression
C Programming by Ali
iskurt
Numerical Computation
in C
28
Assignment Operator
• location ‘=’ value
– Assigns the value from the right side to the
memory location defined by the left
• E.g.,
Assign the value 3 to
the location i
–i = 3
–j = i
– f = sin(x)
– g = expression
C Programming by Ali
iskurt
Numerical Computation
in C
29
Assignment Operator
• location ‘=’ value
– Assigns the value from the right side to the
memory location defined by the left
• E.g.,
Assign the value from
location i to location j
–i = 3
–j = i
– f = sin(x)
– g = expression
C Programming by Ali
iskurt
Numerical Computation
in C
30
Assignment Operator
• location ‘=’ value
– Assigns the value from the right side to the
memory location defined by the left
• E.g.,
–i = 3
–j = i
– f = sin(x)
Apply the sin function
to the value at location x
and store the result in
location f
– g = expression
C Programming by Ali
iskurt
Numerical Computation
in C
31
Assignment Operator
• location ‘=’ value
– Assigns the value from the right side to the
memory location defined by the left
• E.g.,
–i = 3
–j = i
– f = sin(x)
Evaluate the expression
(see below) and store
the result in location g
– g = expression
C Programming by Ali
iskurt
Numerical Computation
in C
32
Note
• A declaration of a variable with an initial
value is equivalent to an assignment to that
variable.
• E.g.,
float b = 3.5;
is the same as
float b;
b = 3.5;
C Programming by Ali
iskurt
Numerical Computation
in C
33
Definition — Expression
• A sequence of operands and operators that,
when evaluated, produce a result value
• Always scanned left-to-right by compiler
– However, precedence of operators may define a
different order of evaluation (see below)
C Programming by Ali
iskurt
Numerical Computation
in C
34
Arithmetic Operators
• Unary – ‘+’ and ‘–’
• Indicates sign of number
• Additive – ‘+’ and ‘–’
• Adds or subtracts two numbers, returns sum or difference
• Multiplicative – ‘*’, ‘/’, and ‘%’
• ‘*’ – multiplies to numbers together, returns product
• ‘/’ – divides first number by second, returns quotient
• ‘%’ – integer division, returns remainder
• …
C Programming by Ali
iskurt
Numerical Computation
in C
35
Arithmetic Expressions
• a*x + b
• c*c + 2*c*d + d*d
• c*c*c + 3*c*c*d + 3*c*d*d + d*d*d
• 1/(1/v1 + 1/v2)
• (minutes1 + minutes2) % 60
C Programming by Ali
iskurt
Numerical Computation
in C
36
Arithmetic Expressions (continued)
• Arithmetic expressions always return a
value of the same type as their operands
• Type conversion rules apply if operands are
of mixed types
• See §A.2, pp. 197-198
• More later
• ‘/’, and ‘%’ are undefined if divisor is zero
C Programming by Ali
iskurt
Numerical Computation
in C
37
Assignment Operator (again)
• ‘=’ — assigns value of the expression on the right
to memory location defined by left
• y = a*x + b;
• i = j + 1;
• z = y = a*x + b;
• Note: assignment is just another operator in an
expression
• Value of the assignment expression is the value assigned
C Programming by Ali
iskurt
Numerical Computation
in C
38
Assignment Expression
• ‘=’ — assigns value of the expression on the
right to memory location defined by left
• Returns the value assigned
• y = a*x + b;
• i = j + 1;
• z = y = a*x + b;
Numerical Computation
Evaluate this expression
first
in C
C Programming by Ali
iskurt
39
Assignment Expression (continued)
• ‘=’ — assigns value of the expression on the
right to memory location defined by left
• Returns the value assigned
• y = a*x + b;
• i = j + 1;
• z = y = a*x + b;
Assign the result here
Numerical Computation
C Programming by Ali
iskurt
in C
40
40
Assignment Expression (continued)
• ‘=’ — assigns value of the expression on the
right to memory location defined by left
• Returns the value assigned
• y = a*x + b;
• i = j + 1;
• z = y = a*x + b;
Assign that result hereNumerical Computation
C Programming by Ali
iskurt
in C
41
41
Questions?
C Programming by Ali
iskurt
Numerical Computation
in C
42
Specifying Symbolic Constants in C
• Two ways
– Textual substitution
– Declaration of const data object
C Programming by Ali
iskurt
Numerical Computation
in C
43
Constant – Textual Substitution
• See page 14 & 89 in K&R
#define NAME replacement-text
• E.g.,
#define PI 3.14159265358979323846
#define LOWER 0
It is traditional in C for textual
#define UPPER 300 substitution names to be all
UPPER CASE
#define STEP 20
C Programming by Ali
iskurt
Numerical Computation
in C
44
Constant – Textual Substitution
• See page 14 & 89 in K&R
#define NAME replacement-text
• E.g.,
#define PI 3.14159265358979323846
When a textual substitution
constant is used in a program,
#define LOWER 0
#define UPPER 300 the compiler simply substitutes
the replacement text on the fly
#define STEP 20
C Programming by Ali
iskurt
Numerical Computation
in C
45
Constant Declaration
const double pi = 3.14159265358979323846;
const double c = 2.99792458e+8;
/* speed of light in meters/sec */
• Defines a value of the declared type with
the declared name
• I.e., creates storage to hold this value
• Must be initialized
• May never be left side of an assignment
C Programming by Ali
iskurt
Numerical Computation
in C
46
Questions?
C Programming by Ali
iskurt
Numerical Computation
in C
47
Introduction to Operator Precedence
• Suppose you encounter the following expressions
in a math, physics, or engineering problem:–
x3  3x 2 y  3xy2  y 3

b 2  4ac
• How do you represent them in C and what order
should the operators be evaluated?
C Programming by Ali
iskurt
Numerical Computation
in C
48
Arithmetic Expressions with
Multiple Operators
x3  3x 2 y  3xy2  y 3
pow(x,3) + 3*pow(x,2)*y + 3*x*pow(y,2)
+ pow(y,3)
1st
5th
2nd
3rd
11th
4th
9th
6th
8th
10th
Value of expression
C Programming by Ali
iskurt
Numerical Computation
in C
49
7th
Exercise – Do the same for this expression

b 2  4ac
• Representation as a C expression
• Order of operations
C Programming by Ali
iskurt
Numerical Computation
in C
50
Definitions
• Operator Precedence
– The relative order in which operators in an
expression in C are executed
• Operator Associativity
– When two operators are of same precedence,
whether the left or right operator is applied first
• See Table 2-1, p. 53
C Programming by Ali
iskurt
Numerical Computation
in C
51
Operator Precedence Table
• A subset of the table is:–
( )
/* highest – function call
and parenthesization */
+ -
/* unary, right to left*/
* / %
/* two operands, left to
right */
+ -
/* two operands, l-to-r*/
=
/* assignment, right to
left */
/* lowest – sequence of
expressions */
,
C Programming by Ali
iskurt
Numerical Computation
in C
52
Operator Precedence
• When scanning an expression …
• A pending operator is not applied until it is
of higher precedence than the next operator
or
• It has the same precedence and associativity
is left-to-right
C Programming by Ali
iskurt
Numerical Computation
in C
53
Arithmetic Expressions with
Multiple Operators
x3  3x 2 y  3xy2  y 3
pow(x,3) + 3*pow(x,2)*y + 3*x*pow(y,2)
+ pow(y,3)
Highest – evaluate within () before anything else
Low – look ahead to see if
next operator is higher
Medium – look ahead to see
if next operator is lower
C Programming by Ali
iskurt
Numerical Computation
in C
54
Warning
• Operator precedence does not specify order
of evaluation of functions
• E.g.,
– x = f(arg1) + g(arg2);
– f and g may be evaluated in either order!
– arg1 and arg2 may be evaluated in either order
• Exceptions:–
– &&, ||, ?:, and ','
C Programming by Ali
iskurt
Numerical Computation
in C
55
How does the compiler implement
precedence?
• Answer:– using a data structure called a
stack
• Definition:– Stack
• A linear data structure comprising a sequence of
items, such that the last item added is the first item
removed
C Programming by Ali
iskurt
Numerical Computation
in C
56
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Detect constant token
representing value 1
• Place value 1 on
value-location stack
1
values&locations
C Programming by Ali
iskurt
operators
Numerical Computation
in C
57
Understanding Operator Precedence
• Discover ‘/’ token
• Example:–
• 1/(1/v1 + 1/v2)
^
1
/
values&locations
operators
C Programming by Ali
iskurt
• Place on operator
stack
Numerical Computation
in C
58
Understanding Operator Precedence
• Discover ‘(’ token
• Example:–
• 1/(1/v1 + 1/v2)
^
– Start of a “sub
expression”
– Highest precedence of
all
• Place matching ‘)’ on
operator stack
1
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
59
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Discover constant
token 1 (again)
• Place on top of valuelocation stack
1
1
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
60
Understanding Operator Precedence
• Discover ‘/’ token
• Example:–
• 1/(1/v1 + 1/v2)
^
– Higher precedence
than ‘(’
• Place ‘/’ on operator
stack
1
1
/
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
61
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Discover identifier
token v1
• Place on valuelocation stack
v1
1
1
/
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
62
Understanding Operator Precedence
• Discover token ‘+’
• Example:–
• 1/(1/v1 + 1/v2)
^
– Note that ‘+’ has lower
precedence than ‘/’
– Cannot place it above ‘/’
• Emit code to calculate
1/v1
– Consumes ‘/’ operator and
top two values from stacks
• Place result on valuelocation stack
• Place on operator stack
v1
1
1
/
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
63
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Stacks now look like
this
1/v1
1
+
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
64
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
1
1/v1
1
+
()
/
values&locations
operators
C Programming by Ali
iskurt
• Discover yet another
value 1
– Place on stack
Numerical Computation
in C
65
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
– Higher precedence
than top of operator
stack
• Place on operator
stack
1
1/v1
1
/
+
()
/
values&locations
operators
C Programming by Ali
iskurt
• Discover yet another
‘/’ operator
Numerical Computation
in C
66
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Place on valuelocation stack
v2
1
1/v1
1
/
+
()
/
values&locations
operators
C Programming by Ali
iskurt
• Discover yet another
identifier v2
Numerical Computation
in C
67
Understanding Operator Precedence
• Discover ‘)’ token
• Example:–
• 1/(1/v1 + 1/v2)
^
v2
1
1/v1
1
/
+
()
/
values&locations
operators
C Programming by Ali
iskurt
– Finish all operations
back to ‘()’
Numerical Computation
in C
68
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Emit code to do ‘/’
operation
– Consumes top two
values on the stack
• Places result on value
location stack
v2
1
1/v1
1
/
+
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
69
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
1/v2
1/v1
1
+
()
/
values&locations
operators
C Programming by Ali
iskurt
• Emit code for ‘+’
operation
– Places result (i.e., sum)
on value location stack
Numerical Computation
in C
70
Understanding Operator Precedence
• Delete ‘()’
• Example:–
• 1/(1/v1 + 1/v2)
^
sum
1
()
/
values&locations
operators
C Programming by Ali
iskurt
Numerical Computation
in C
71
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
sum
1
/
values&locations
operators
C Programming by Ali
iskurt
• Discover end of
expression
• Emit code for ‘/’
operation
• Place result on value
location stack
Numerical Computation
in C
72
Understanding Operator Precedence
• Example:–
• 1/(1/v1 + 1/v2)
^
• Final result is value of
the expression
1/sum
values&locations
C Programming by Ali
iskurt
operators
Numerical Computation
in C
73
Questions?
C Programming by Ali
iskurt
Numerical Computation
in C
74