740 likes | 797 Vues
Numerical Computation in C. CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based on/ borrowed from Professor Hugh C. Lauer.
E N D
Numerical Computation in C CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based on/borrowed from Professor Hugh C. Lauer. 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) Numerical Computation in C
Reminder – Reading Assignment • Chapter 2 — Overview of C • §2.1 – Getting Started • §2.2 – Variables and Arithmetic Expressions • §2.5 – Types, Operators, and Expressions Numerical Computation in C
Review:– C is a “typed” language Numerical Computation in C • 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 • …
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 Numerical Computation in C
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 Numerical Computation in C
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 Numerical Computation in C
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? Numerical Computation in C
Floating Point Representation • 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 S exponent mantissa Numerical Computation in C
Floating Point Representation (continued) There is also a long double type – 128 bits total. • float f; • 1 sign bit • 8 exponent bits • 23 mantissa bits • double g; • 1 sign bit • 11 exponent bits • 52 mantissa bits • Value of floating point number • 1.m0m1m2…m22 2(exp-127) // float • 1.m0m1m2……m51 2(exp-1023) // double 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. Numerical Computation in C
l r 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 Numerical Computation in C
#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″ ″:- ″); 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 Concatenation of string constants Simple Program Example (continued) Numerical Computation in C
Rarely used! 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 Numerical Computation in C
Not allowed! Okay! 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 …" Numerical Computation in C
Digression:– Coding Conventions (cont.) • Comments • Any sequence of characters between "/*" and "*/" • 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 Numerical Computation in C
#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″ ″:- ″); 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 Simple Program Example (continued) Numerical Computation in C
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 Numerical Computation in C
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” Numerical Computation in C
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 Definitions of Numeric Data Numerical Computation in C
unsigned int i; int j, k; short m = 0; long n = m; … Allocate two memory locations big enough to hold an integer. Names of those locations are j and k Cannot count on them being in contiguous locations Definitions of Numeric Data Numerical Computation in C
unsigned int i; int j, k; short m = 0; long n = m; … Allocate a memory location big enough to hold a short integer. i.e., short int m = 0 Name of that location is m Initialize the value of that location to 0 Definitions of Numeric Data Numerical Computation in C
unsigned int i; int j, k; short m = 0; long n = m; … 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 Definitions of Numeric Data Numerical Computation in C
unsigned int i; int j, k; short m = 0; long n = k; … What if we had tried to initialize it to k instead? What would value of n be? Definitions of Numeric Data Numerical Computation in C
double a; float b = 3.5; float d = 9.3e6; double e = 2.1e-8; … Same as previous, but for floating point data Definitions of Numeric Data (continued) Numerical Computation in C
double a; float b = 3.5; float d = 9.3e6; double e = 2.1e-8; … Same as previous, but for floating point data Note the decimalized notation for the initialization Definitions of Numeric Data (continued) Numerical Computation in C
double a; float b = 3.5; float d = 9.3e6; double e = 2.1e-8; … Same as previous, but for floating point data Scientific notation for initializations – i.e., 9.3 106 2.1 10-8 Definitions of Numeric Data (continued) Numerical Computation in C
Questions? Numerical Computation in C
Assignment Operator Note: computer scientists often refer to the location as the l-value (i.e., left value;) Numerical Computation in C • 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) • g = expression
Assignment Operator Assign the value 3 to the location i Numerical Computation in C • 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) • g = expression
Assignment Operator Assign the value from location i to location j Numerical Computation in C • 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) • g = expression
Assignment Operator Apply the sin function to the value at location x and store the result in location f Numerical Computation in C • 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) • g = expression
Assignment Operator Evaluate the expression (see below) and store the result in location g Numerical Computation in C • 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) • g = expression
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; Numerical Computation in C
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) Numerical Computation in C
Arithmetic Operators Numerical Computation in C • 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 • …
Arithmetic Expressions Numerical Computation in C • 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
Arithmetic Expressions (continued) Numerical Computation in C • 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
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 Numerical Computation in C
Assignment Expression Evaluate this expression first Numerical Computation in C • ‘=’ — 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;
Assignment Expression (continued) Assign the result here Numerical Computation in C • ‘=’ — 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; 39
Assignment Expression (continued) Assign that result here Numerical Computation in C • ‘=’ — 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; 40
Questions? Numerical Computation in C
Specifying Symbolic Constants in C • Two ways • Textual substitution • Declaration of const data object Numerical Computation in C
Constant – Textual Substitution #define NAME replacement-text • E.g., #define PI 3.14159265358979323846 #define LOWER 0#define UPPER 300#define STEP 20 It is traditional in C for textual substitution names to be all UPPER CASE Numerical Computation in C
Constant – Textual Substitution #define NAME replacement-text • E.g., #define PI 3.14159265358979323846 #define LOWER 0#define UPPER 300#define STEP 20 When a textual substitution constant is used in a program, the compiler simply substitutes the replacement text on the fly Numerical Computation in C
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 Numerical Computation in C
Questions? Numerical Computation in C
Introduction to OperatorPrecedence • Suppose you encounter the following expressions in a math, physics, or engineering problem:– • How do you represent them in C and what order should the operators be evaluated? Numerical Computation in C
1st 4th 10th 2nd 5th 3rd 9th 6th 8th 7th 11th Arithmetic Expressions withMultiple Operators pow(x,3) + 3*pow(x,2)*y + 3*x*pow(y,2)+ pow(y,3) Value of expression Numerical Computation in C
Exercise – Do the same for this expression • Representation as a C expression • Order of operations Numerical Computation in C
Definitions A very important topic. Easy to get tripped up. Source of lots of errors! • 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 Numerical Computation in C