Lec05 - The Ohio State University

CSE1222: Lecture 4
The Ohio State University
1
Mathematical Functions (1)
ž 
The math library file cmath
—  Yes, this is a file with definitions for common and often
used mathematical functions including:
sine, cosine, log, and square root
—  Provided by our C++ geniuses (Be thankful!)
ž 
Using the math library
—  Include the following at the top of your program
#include <cmath>
CSE1222: Lecture 4
The Ohio State University
2
Mathematical Functions (1)
ž 
How do you use or invoke a function in math?
Specify …
— 
— 
Its name
Input parameters
Retrieve its …
— 
ž 
Output or answer
Remember y = f(x) from math?
—  f is the name
—  x is the input parameter
—  y will hold the output
ž 
A function has three parts: Name, input, and output
CSE1222: Lecture 4
The Ohio State University
3
Mathematical Functions (1)
ž 
The cmath library defines a function called sqrt … What do you
think it does?
—  Function names are descriptive
—  Function names must be spelled exactly how they are defined in their
defining library (cmath here, so don’t guess! Look it up)
—  You must provide exactly how many input parameters a function is
defined to take
—  A function can output at most one answer only
ž 
The square root function :
—  Spelled sqrt
—  Requires exactly one input parameter (a number)
—  Outputs the square root of the input parameter
ž 
Question: Where does the output or answer go???
CSE1222: Lecture 4
The Ohio State University
4
Mathematical Functions (2)
ž 
This function invocation:
double a = 81;
double b = sqrt(a);
—  Takes the value of the variable a as a single input parameter
—  Executes the computation for a square root
—  “Outputs” its answer in the assignment statement
Rule (Memorize this!): The output value of a function invocation will
relace the syntax of the function call in your program during
program execution
ž 
During execution of this code the second line will execute in the following way:
double b = sqrt(a);
<---- Before execution
double b = sqrt(81);
double b = 9.0;
<---- Evaluates the input parameter
<---- This line uses the rule above
CSE1222: Lecture 4
The Ohio State University
5
Mathematical Functions (2)
ž 
Is this program snippet nonsensical … Why or why not?
double a = 81;
sqrt(a);
Is there a syntax error, i.e. will it compile?
- No syntax error! But, avoid invoking a function in this way if it outputs a value.
You are throwing away the output!
ž 
Is there a syntax error? Is it nonsensical?
double a = 81;
cout << sqrt(a);
No syntax error! If a function invocation outputs a value, then ensure that the syntax
of the function call is used with other code that performs useful work
ž 
This statement would output 11
cout << sqrt(121.0) << endl;
CSE1222: Lecture 4
The Ohio State University
6
Mathematical Functions (2)
ž 
Is there a syntax error?
double a = 81;
double b = sqrt(a);
double c = sqrt(sqrt(a)) * b;
ž 
No syntax error! A function can be used like a variable of the same
data type
ž 
Remember our rule regarding the output of a function invocation
—  How is it used here to evaluate the third line?
ž 
Here, a is 81, b is 9, and c is 27. Why?
—  The sqrt function is called three separate times in this code snippet
—  Which function is invoked first, which is invoked second, and then which
is invoked third?
CSE1222: Lecture 4
The Ohio State University
7
Mathematical Functions (3)
ž 
What does the cmath library function pow do?
—  Computes ab, where a and b are two numbers
—  Its name tries to tell you what operation the function performs for you
ž 
How many input parameters does this function require?
— 
ž 
We need a base and an exponent, so two input parameters
Does this function output a single answer or no answer?
—  It must return the value for ab, so one answer
ž 
For example
cout << pow(3.0, 4.0);
would output 81 which is 3 to the 4th power.
Notice the two input parameters in the parenthesis (comma
separated). The base must come BEFORE the power!
CSE1222: Lecture 4
The Ohio State University
8
Mathematical Functions (4)
ž 
Arguments passed into any function can be a
constant, variable, or an expression that
evaluates to the appropriate data type
ž 
For Example,
double j = 2.0;
cout << sqrt(j * 32.0);
//outputs 8
Remember, the sqrt function requires exactly one argument
CSE1222: Lecture 4
The Ohio State University
9
Mathematical Functions (5)
ž 
Functions can themselves be part of an
expression
double x = 10;
cout << 5 * pow( (x - 3), 2.0 );
//output?
Remember our rule regarding function output and
where it goes?
Remember, the pow function requires exactly two arguments
CSE1222: Lecture 4
The Ohio State University
10
Common Math Functions
Function
Returned Value
Data Type of
Returned Value
abs(a)
Absolute value of a
Data type of a
pow(b,e)
Value of b raised to the eth power
float or double
Data type of b
sqrt(a)
Square root of a
double
sin(a)
Sine of a in radians
double
cos(a)
Cosine of a in radians
double
tan(a)
Tangent of a in radians
double
log(a)
Natural log of a
double
log10(a)
Common log (base 10) of a
double
exp(a)
e raised to the ath power
double
CSE1222: Lecture 4
The Ohio State University
11
Example: sqrt()
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x(0.0), y(0.0);
double dist(0.0);
cout << "Enter x, y: ";
cin >> x >> y;
dist = sqrt(x * x + y * y);
cout << "Distance of (" << x << "," << y << ") to (0,0) = " <<
dist << endl;
}
return 0;
// What are we computing here (in plain english)?
// Compile and execute after class!
CSE1222: Lecture 4
The Ohio State University
12
…
cout << "Enter x, y: ";
cin >> x >> y;
dist = sqrt(x * x + y * y);
cout << "Distance of (" << x << "," << y << ") to (0,0) =
"
<< dist << endl;
…
> distance.exe
Enter x, y: 3 4
Distance of (3,4) to (0,0) = 5
> distance.exe
Enter x, y: 5 8
Distance of (5,8) to (0,0) = 9.43398
CSE1222: Lecture 4
The Ohio State University
13
Example 2: sqrt()
#include <iostream>
#include <cmath>
// math function library
using namespace std;
int main ()
{
double height(0), time(0.0);
cout << "Enter height (feet): ";
cin >> height;
time = sqrt(2.0 * height / 32.2);
cout << "It will take " << time << " seconds to fall "
<< height << " feet. " << endl;
}
return 0;
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
14
…
cout << "Enter height (feet): ";
cin >> height;
time = sqrt(2.0 * height / 32.2);
cout << "It will take " << time << " seconds to fall "
<< height << " feet. " << endl;
…
> gravity.exe
Enter height: 100
It will take 2.49222 seconds to fall 100 feet.
> gravity.exe
Enter height (feet): 500
It will take 5.57278 seconds to fall 500 feet.
CSE1222: Lecture 4
The Ohio State University
15
Example: log()
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double rate(0.0), years(0.0);
cout << "Enter annual interest rate (percentage): ";
cin >> rate;
years = log(2.0) / log(1 + (rate / 100.0));
cout << "Your money will double in " << years
<< " years." << endl;
}
return 0;
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
16
…
…
cout << "Enter annual interest rate (percentage): ";
cin >> rate;
years = log(2.0) / log(1 + (rate / 100.0));
cout << "Your money will double in " << years
<< " years." << endl;
> interest.exe
Enter annual interest rate (percentage): 7
Your money will double in 10.2448 years.
> interest.exe
Enter annual interest rate (percentage): 2
Your money will double in 35.0028 years.
CSE1222: Lecture 4
The Ohio State University
17
Trigonometric Math Functions
ž  Read
your documentation on functions!
ž  Trigonometric
math functions (such as
sin, cos, and tan) require input
parameters to be in radians
CSE1222: Lecture 4
The Ohio State University
18
Example: sin(), cos()
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double angle(0.0), x(0.0), y(0.0);
cout << "Enter rotation angle (radians): ";
cin >> angle;
x = cos(angle);
y = sin(angle);
cout << "Point (1,0) rotates to point"
<< "(" << x << "," << y << ")" << endl;
}
return 0;
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
19
…
…
cout << "Enter rotation angle (radians): ";
cin >> angle;
x = cos(angle);
y = sin(angle);
cout << "Point (1,0) rotates to point"
<< "(" << x << "," << y << ")" << endl;
> rotate_radians.exe
Enter rotation angle (radians): 1.57
Point (1,0) rotates to point (0.000796327,1)
> rotate_radians.exe
Enter rotation angle (radians): 0.78
Point (1,0) rotates to point (0.710914,0.703279)
CSE1222: Lecture 4
The Ohio State University
20
Common Math Constants
ž 
Besides functions, the cmath library file also defines some
commonly used math constants
ž 
Use these like variables
—  Though, being “constants” you cannot assign a new value to
them
Constant
Value
M_PI
π, 3.14159…
M_E
e, the base of natural logarithms
M_LOG2E
Base-2 logarithm of e
M_LOG10E
Base-10 logarithm of e
M_LN2
Natural log of 2
M_LN10
Natural log of 10
CSE1222: Lecture 4
The Ohio State University
21
degrees2radians.cpp
#include <iostream>
#include <cmath>
using namespace std;
// cmath contains definitions of math constants
int main()
{
double degrees(0.0), radians(0.0);
cout << "Enter angle in degrees: ";
cin >> degrees;
radians = (degrees * M_PI) / 180.0; // Convert degrees to radians
cout << "Angle in radians = " << radians << endl;
return 0;
}
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
22
rotate_degrees.cpp
#include <iostream>
#include <cmath> // cmath contains definitions of math constants
using namespace std;
int main()
{
double degrees(0.0), radians(0.0), x(0.0), y(0.0);
cout << "Enter rotation angle (degrees): ";
cin >> degrees;
radians = (degrees * M_PI) / 180.0;
x = cos(radians);
y = sin(radians);
cout << "Point (1,0) rotates to point (" << x << "," << y <<
")" << endl;
}
return 0;
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
23
…
…
cout << "Enter rotation angle (degrees): ";
cin >> degrees;
radians = (degrees * M_PI) / 180.0;
x = cos(radians);
y = sin(radians);
cout << "Point (1,0) rotates to point"
<< "(" << x << "," << y << ")" << endl;
> rotate_degrees.exe
Enter rotation angle (degrees): 90
Point (1,0) rotates to point (6.12323e-17,1)
> rotate_degrees.exe
Enter rotation angle (degrees): 45
Point (1,0) rotates to point (0.707107,0.707107)
CSE1222: Lecture 4
The Ohio State University
24
log_2.cpp
#include <iostream>
#include <cmath> // cmath contains definitions of math constants
using namespace std;
int main()
{
double x(0.0), y(0.0);
cout << "Enter number: ";
cin >> x;
y = log(x) / M_LN2;
cout << "log_e(" << x << ") = " << log(x) << endl;
cout << "log_2(" << x << ") = " << y << endl;
}
return 0;
// What are we computing here (in plain english)?
CSE1222: Lecture 4
The Ohio State University
25
Arguments to Math Functions
ž 
Input parameters (i.e., arguments) to math
functions should have type double
ž 
For example,
double x(3.6), y(0.3), z(0.0);
z
z
z
z
CSE1222: Lecture 4
=
=
=
=
sin(1.2);
sqrt(x);
log(3.2 * x);
pow(x / 0.5, 1.2 * y);
The Ohio State University
26
logError.cpp
. . .
int main()
{
int value(0);
cout << "Enter value: ";
cin >> value;
// log(value) generates a compiler error
cout << "At 10% interest, it will take " << log(value)/
log(1.1) <<
" years for a $1 investment to be worth $" << value << "."
<< endl;
return 0;
}
CSE1222: Lecture 4
The Ohio State University
27
…
15. 
16. 
17. 
18. 
// log(value) generates a compiler error
cout << "At 10% interest, it will take " << log(value) / log(1.1)
<< " years for a $1 investment to be worth $" << value << "." <<
endl;
…
// What is the problem here? What is the data type for variable “value”?
> g++ logError.cpp –o logError.exe
Compiling logError.cpp into logError.exe.
logError.cpp: In function 'int main()':
logError.cpp:16: call of overloaded 'log(int&)' is ambiguous
/usr/include/iso/math_iso.h:52: candidates are: double log(double)
/usr/local/include/g++-v3/bits/std_cmath.h:333:
long double
std::log(long double)
/usr/local/include/g++-v3/bits/std_cmath.h:323:
float
std::log(float)
CSE1222: Lecture 4
The Ohio State University
28
logExample.cpp
. . .
int main()
{
int value(0);
double x(0.0);
cout << "Enter value: ";
cin >> value;
x = value;
// implicit conversion to double
cout << "At 10% interest, it will take " << log(x)/
log(1.1)
<< " years for a $1 investment to be worth $" <<
value << "." << endl;
}
return 0;
// Will this do the trick?
CSE1222: Lecture 4
The Ohio State University
29
…
double x(0.0);
...
x = value;
// implicit conversion to double
cout << "At 10% interest, it will take " << log(x)/
log(1.1)
<< " years for a $1 investment to be worth $" <<
value << "." << endl;
…
> logExample.cpp
Enter value: 10
At 10% interest, it will take 24.1589 years for a $1 investment to be worth $10.
>
CSE1222: Lecture 4
The Ohio State University
30
CSE1222: Lecture 4
The Ohio State University
31
Modulus Operator: %
ž 
In math a mod b is the remainder after integer a is
divided by integer b
ž 
You can think of this operator as a function: 1) name
(%), two operands (two integer input parameters),
one output (an integer)
ž 
In C++ a mod b is written as:
a % b
Examples:
25 % 3 = ?
137 % 10 = ?
2751 % 2 = ?
ž 
CSE1222: Lecture 4
The Ohio State University
32
Expression Types
ž 
An expression consists of constants, variables,
and function invocations that output single
values and evaluates to a single answer
—  For example,
5 * pow( (x - 3), 2.0 )
ž 
An expression that contains only integer
operands is an integer expression
ž 
An expression that contains only floating point
operands is a floating-point expression
CSE1222: Lecture 4
The Ohio State University
33
Mixing Expression Types
ž 
A mixed-mode expression has both
floating-point and integer data types
ž 
The rules governing the data type of
the result are:
1.  If both operands are integers, the result is an
integer
2.  If one operand is a floating-point number, then
the result is a double
CSE1222: Lecture 4
The Ohio State University
34
Mixed Mode Expressions
int a(3);
double x(3.5), y(5), z(0.0);
z = 3.0 * 25;
z = a * x;
z = a * y;
What about:
z = x + (a / 2);
CSE1222: Lecture 4
The Ohio State University
35
Exercises
int a(3), b(2);
double y(5), z(0.0);
After each operation, what is z?
z
z
z
z
z
CSE1222: Lecture 4
=
=
=
=
=
(y + a) / b;
(y * a) / b;
y * (a / b);
(y / b) * (a / b);
(a + b) / (b * y);
The Ohio State University
36
logError.cpp
. . .
int main()
{
int value(0);
cout << "Enter value: ";
cin >> value;
// log(value) generates a compiler error
cout << "At 10% interest, it will take " <<
log(value)/log(1.1)
<< " years for a $1 investment to be worth $" <<
value << "." << endl;
}
return 0;
CSE1222: Lecture 4
The Ohio State University
37
logExample2.cpp
. . .
int main()
{
int value(0);
cout << "Enter value: ";
cin >> value;
// Mixed mode expression "value * 1.0" returns double.
cout << "At 10% interest, it will take " <<
log(value * 1.0)/log(1.1)
<< " years for a $1 investment to be worth $" <<
value << "." << endl;
return 0;
}
CSE1222: Lecture 4
The Ohio State University
38
CSE1222: Lecture 4
The Ohio State University
39
Evaluate
ž  What
does this express evaluate to?
1 + 3 * 6 – 4 / 2 = ???
Try it out on a sheet of paper
CSE1222: Lecture 4
The Ohio State University
40
Evaluate
ž 
What does this express evaluate to?
20 – 16 / 2 + 2 * 3 = ???
ž 
What if we insert parenthesis in different
places?
(((20 – 16) /2) +2) * 3 = 12
ž  ((20 – 16) / (2 + 2)) * 3 = 3
ž  20 – ((16/2) + (2*3)) = -4
ž 
CSE1222: Lecture 4
The Ohio State University
41
Operator Precedence and Associativity
ž 
The minus sign is overloaded
—  Used as a binary operator for subtraction
—  Used as a unary operator to negate the sign
ž 
How do you know which one you are using?
—  int a = b – c;
—  int a = - c;
ž 
<---- Is this negation?
<---- Is this negation?
Depends on the context, operator precedence, and
associativity rules
CSE1222: Lecture 4
The Ohio State University
42
Operator Precedence and Associativity
ž 
Expressions are evaluated from left to right
ž 
If there is an ambiguity, then operator
precedence determines which operators is
evaluated first
Precedence
() Unary */%
+-
CSE1222: Lecture 4
Associativity
Left to right
Left to right
The Ohio State University
43
arithmetic3.cpp
// Precedence of arithmetic operators
#include <iostream>
using namespace std;
int main()
{
cout << "-3+5*2 = " << -3+5*2 << endl << endl;
// Is this?
cout << "((-3)+5)*2
cout << "(-(3+5))*2
cout << "(-3)+(5*2)
cout << "-(3+(5*2))
=
=
=
=
"
"
"
"
<<
<<
<<
<<
((-3)+5)*2
(-(3+5))*2
(-3)+(5*2)
-(3+(5*2))
<<
<<
<<
<<
endl;
endl;
endl;
endl;
return 0;
}
CSE1222: Lecture 4
The Ohio State University
44
Math in C++ Review
ž 
Use #include<cmath> for math functions
ž 
Common math functions:
abs(a), pow(b,e), sqrt(a), sin(a), cos(a), tan(a),
log(a), log10(a), exp(a)
ž 
Common math constants:
M_PI, M_E, M_LN2, M_LN10
CSE1222: Lecture 4
The Ohio State University
45
Math in C++ Review
ž 
Arguments to functions should always be double
ž 
Mixed mode operations:
(3.0 + 5) or (3.0 * 5) have type double;
ž 
Operator precedence:
Multiplication and division before addition and
subtraction
CSE1222: Lecture 4
The Ohio State University
46