Computer Programming: Skills & Concepts (CP) Arithmetic

advertisement
Computer Programming: Skills & Concepts (CP)
Arithmetic operations, int, float, double
M. Cryan
29th September, 2015
CP Lect 4 – slide 1 – 29th September, 2015
Monday’s lecture
I
Variables and change-of-state
I
The “squaring” problem.
I
Types of variables: int.
I
Assigning and re-assigning values to a variable.
I
The if-statement.
I
Input using scanf.
CP Lect 4 – slide 2 – 29th September, 2015
Today’s lecture
I
Arithmetic Operations for int
I
Quadratic Equations.
I
More types: float and double.
I
General form of if-statement.
CP Lect 4 – slide 3 – 29th September, 2015
Arithmetic Operators for int
+
Addition.
−
Subtraction or negation.
*
Multiplication (don’t use ‘x’).
/
Division - order is important here!
I What is 4/2?
I What is 5/2?
%
Integer remainder (eg, 5 % 3 = 2).
I
I
% is an overloaded symbol.
Where else have you seen it?
++
Increment (x++ means x = x+1).
−−
Decrement (x-- means x = x-1).
ˆ (sometimes used in “real life” for powers - eg, xˆ3) is NOT an arithmetic
operation in the C programming language - for powers, use the * operator
(repeatedly) or the pow function from math.h.
CP Lect 4 – slide 4 – 29th September, 2015
Solving quadratic equations
Consider any quadratic polynomial of the form ax 2 + bx + c, a 6= 0.
We know this equation has exactly two complex roots (solutions to
ax 2 + bx + c = 0) given by:
√
−b ± b 2 − 4ac
.
x=
2a
Suppose we want real roots ONLY.
Three cases:
I
If b 2 < 4ac, there are no real solutions.
I
If b 2 = 4ac, there is one (duplicate) real solution: −b/(2a).
I
If b 2 > 4ac, there are two different real solutions.
CP Lect 4 – slide 5 – 29th September, 2015
C program to Solve Quadratic Equations
x=
−b ±
√
b 2 − 4ac
.
2a
Steps of our program:
I
I
Take in the inputs a, b and c from the user (scanf).
check that b 2 − 4ac is non-negative.
I
I
If negative, output a message about “No real roots”.
If positive, proceed.
I
Get the square root of b 2 − 4ac.
I
Output both roots (or one if duplicate).
I
return EXIT SUCCESS;
We cannot continue working with int variables only.
We do not expect the roots to be integers even when a, b, c are.
CP Lect 4 – slide 6 – 29th September, 2015
Real numbers in C
For working with “real numbers” in C, there are two options:
float and double. Neither type can truly represent all real
numbers - both types have a limited number of significant
digits. But they work well as an approximation for reals.
We will require the coefficients input for the quadratic equation to be
int. However we will also need some float or double variables for the
roots.
CP Lect 4 – slide 7 – 29th September, 2015
Types: float
I
A signed floating-point number: numbers with decimal points.
I
Form to write a float is
hni.hmiehki
I
where hni, hki are integers (can have a - sign in front) and hmi is a
positive number (no sign allowed).
For example:
I
I
I
Accurate to about 7 significant digits:
I
I
I
I
Max value is 3.40282347 ∗ 1038 on DICE (system dependent);
Requires the same amount of storage as int.
Contrast with real numbers in mathematics?
printf("%f", floatVar) and scanf("%f", &floatVar).
I
I
1.5, -2.337, 6e23 (having values 1.5, -2.337 and 6 × 1023 )
0.0, 0., .0 (all of these have value 0.0)
%f means “float”
Stored in 32-bit sign(1)/exponent(8)/mantissa(23) representation.
CP Lect 4 – slide 8 – 29th September, 2015
Types: double
I
A float with double precision.
I
Same form for writing double as float in programs.
Accurate to about 15 significant digits:
I
I
I
I
I
I
Print with printf("%f", doubleVar);
BUT scan with scanf("%lf", &doubleVar);
I
I
I
Max value is 1.7976931348623157 ∗ 10308 ;
Requires twice the storage space as float;
Values may depend on your computer.
The %lf means “long float”
Our version of gcc also allows %lf in printf.
Stored in 64-bit sign(1)/exponent(11)/mantissa(52) representation.
CP Lect 4 – slide 9 – 29th September, 2015
Writing float/double in programs
#include <stdlib.h>
#include <stdio.h>
int main(void) {
float x, x2;
double y, y2;
x = 6e5;
x2 = -0.2223;
y = 5e-8;
y2 = -6e306;
printf("Two floats are %f\n and %f.\n", x, x2);
printf("Two doubles are %2.9f\n and %f.\n", y, y2);
return EXIT_SUCCESS;
}
CP Lect 4 – slide 10 – 29th September, 2015
Output from float/double
[fletcher]mcryan: ./a.out
Two floats are 600000.000000
and -0.222300.
Two doubles are 0.000000050
and -6000000000000000415146435945218699544294763362085459842
0126115503945248872404569187418808157783928463113189413945180
4157162361475827507299487506852076765339123136457002148018714
2842148415306933169404320733422827669951287867963409490577301
3933547655429167101887147924700636668768497796837912298082360
15124480.000000.
If we did not have %2.9f in the printf, we would only get 6 decimal
spaces for y (would look like 0).
Is there a mistake in the printing out of y2?
No! The first 16 digits are correct (double guarantees the first 15).
CP Lect 4 – slide 11 – 29th September, 2015
Mixing Types and casting
What happens when we divide a float by an int?
3.0/2 = ?
This will always perform “real” division if either the numerator (top) or
denominator (bottom) are of type float or double.
For an simple expression, where the top and bottom are single expressions,
it is enough to include one number of floating point type.
If the expressions are more complex, and/or involve a number of variables,
you are safest casting with (float). For example, the following two
expressions can evaluate to quite different expressions, as the presence
of the 3.0 is not sufficient to force the (x/z) to be evaluated as a float
(evaluation is left-to-right):
(x/z)*3.0/2
((float)x/(float)z)*3.0/2
If in doubt, cast explicitly with (float) or (double).
CP Lect 4 – slide 12 – 29th September, 2015
Choice of variables for quadratic.c
I
We will need to compute the square-root of b 2 − 4ac.
I
The sqrt function available in the math library for C is of the type
double sqrt (double x);
I
For this simple reason we use double variables for our real roots.
I
Precision is not really important to us, at least not now.
CP Lect 4 – slide 13 – 29th September, 2015
C program to Solve Quadratic Equations
x=
−b ±
√
b 2 − 4ac
.
2a
Steps of our program:
I
Take in the inputs a, b and c from the user (scanf).
Need three int variables to store these values: a, b, c say;
I
test whether b 2 − 4ac is non-negative.
What we do will depend on the result of the test
I
I
I
If negative, output a message about “No real roots”.
If exactly 0, a “double root”
Otherwise, two differing roots as per formula.
I
Get the square root of b 2 − 4ac (if non-negative).
I
Output both roots (or one if duplicate).
I
return EXIT SUCCESS;
CP Lect 4 – slide 14 – 29th September, 2015
body of quadratic.c
s = (b*b -4*a*c);
if (s < 0) {
printf("No real roots to this quadratic.\n");
} else if (s == 0) {
printf("Eq. has the double root %f.\n", -((double)b)/(2.0*a));
} else {
x1 = (-(double)b - sqrt((double)(s)))/(2.0*a);
x2 = (-(double)b + sqrt((double)(s)))/(2.0*a);
}
printf("The sols to %dx^2 +%dx +%d = 0 are ", a, b, c);
printf("%f and %f.\n", x1, x2 );
CP Lect 4 – slide 15 – 29th September, 2015
Running quadratic.c
note: Not enough to include <math.h>
I
This is just a header file for the math library.
I
Must also add -lm to gcc options:
gcc -Wall -lm quadratic.c
CP Lect 4 – slide 16 – 29th September, 2015
Assumptions :-(
We made some assumptions for quadratic.c
I
By solving a quadratic, we (implicitly) assumed a is non-zero.
I
Same for b.
I
We might have had a linear or constant equation.
SOLUTION - use the (general) if statement.
CP Lect 4 – slide 17 – 29th September, 2015
Reading material
Sections 2.8, 2.9, 2.10, 2.11 of “A book on C” discuss Operators, Operator
precedence, and assignments (ie, material from Monday’s lecture).
Section 3.6 (The Floating Types) of “A Book on C”.
Section 4.7 (The if and the if-else statements) of “A Book on C”.
CP Lect 4 – slide 18 – 29th September, 2015
Download