forked from jeremyhansen/rooksguide-cplusplus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chap_advancedarith.tex
237 lines (189 loc) · 9.26 KB
/
chap_advancedarith.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
% This work by Jeremy A. Hansen is licensed under a Creative Commons
% Attribution-NonCommercial-ShareAlike 3.0 Unported License,
% as described at http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode
Advanced arithmetic in C++ includes mathematics that can't be used in code without the use of the \Code{<cmath>} library.
This is mathematics that goes above and beyond the primitive operations: addition (\Code{+}), subtraction (\Code{-}), multiplication (\Code{*}), and division (\Code{/}).
As we have seen before, some simple arithmetic might look like:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x;
x = 1;
x += 5;
\end{lstlisting}\end{minipage}
The variable \Code{x} is declared as an integer.
The next line sets it to one.
The \Code{+=} operator adds five to \Code{x}, which makes \Code{x} contain six.
Doing simple operations like these does not require any special libraries or unusual commands.
Any compiler can look at a \Code{+}, \Code{-}, \Code{*}, or \Code{/} in a line of code and know exactly what the programmer
expects to happen.
Some math requires a little extra help, though.
In this case, help is the \Code{<cmath>} library.
\Code{<cmath>} is a library that is needed for trigonometric, hyperbolic, exponential, logarithmic, rounding, and absolute value functions.
The \Code{<cmath>} library is designed to make your life simple and to make complicated mathematics easier in C++.
Using the \Code{<cmath>} library in code is as simple as including it at the top of your source code file with the rest of your libraries.
For example:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
#include <iostream>
#include <cmath>
\end{lstlisting}\end{minipage}
After the inclusion of the \Code{<cmath>} library, you can use certain mathematical functions in your code such as \Code{pow(x, y)}, which raises the parameter \Code{x} to the power of parameter \Code{y}, and \Code{sqrt(z)}, which returns the square root of \Code{z}.
In your first few C++ programs you will probably not use the more advanced mathematical functions included in the \Code{<cmath>} library, but for a full list of the functions provided in \Code{<cmath>}, refer to ``Further Reading'' at the end of this chapter.
\LevelD{Examples}
\LevelE{\Code{pow()}}
\Code{pow} is the function called when you want to raise a value or variable to a certain power.
Take a look at the code below and we'll break it down line by line.
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x, y;
x = 4;
y = pow(x + 1, 3) + 6;
\end{lstlisting}\end{minipage}
First, we are declaring two variables: \Code{x} and \Code{y}.
After that we set \Code{x} to 4.
Now we get to a more interesting section of code.
We are asking the compiler to raise the value of \Code{x} plus 1 to the power of 3, add 6, and then place the result in \Code{y}.
To use the \Code{pow} function, you must understand its syntax.
Here is the breakdown:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
pow (starting value, power being raised)
\end{lstlisting}\end{minipage}
In \Code{pow(x + 1, 3) + 6}, we are raising the starting value \Code{x}~+~1 to the power of 3.
Before the power of 3 is applied, 1 is added to \Code{x}.
In this case it is the simple operation of 4+1, which yields 5.
After we get 5, we raise it to the 3\textsuperscript{rd} power to get a value of 125.
After we reach the value of 125 we are finished with the \Code{pow} function and resume using normal operators when we add 6 to 125 resulting in the final value of 131.
Undoubtedly there are more complicated uses of the \Code{pow} function, such as multiple uses of \Code{pow} in the same line of code.
You might use multiple \Code{pow} operations in code that calculates the length of one side of a triangle using the Pythagorean Theorem.
Look at the following code and see if you can figure out what the output value would be:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x, y, z;
x = 3;
y = x + 1;
z = pow(x, 2) + pow(y, 2);
cout << z;
\end{lstlisting}\end{minipage}
If you got 25, then you have the right answer!
After initializing the variables \Code{x} and \Code{y} and setting their values (3 for \Code{x} and \Code{x}+1 for \Code{y}), we raise each value to the power of 2.
For visual reference,
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
z = pow (3, 2) + pow (x+1, 2);
\end{lstlisting}\end{minipage}
results in
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
z = 9 + 16;
\end{lstlisting}\end{minipage}
\Code{z}'s value is set to 25.
The \Code{pow} function is simple to use and can make the program simpler from a readability standpoint.
\LevelE{\Code{sqrt()}}
Square roots are calculated using the \Code{sqrt} function.
Take a look at the example below to see how it is called in a program:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int a, b;
a = 25;
b = sqrt(a);
\end{lstlisting}\end{minipage}
\Code{sqrt} is simpler than \Code{pow} in that it only requires one parameter.
Since \Code{sqrt} returns a \Code{double}, you should usually assign the result to a \Code{double} variable, but in this example, \Code{sqrt} returns exactly 5, so it is implicitly converted to an \Code{int} without any issues.
There are cases where both \Code{sqrt} and \Code{pow} are used in the same formula, such as when calculating the distance between two points.
When writing such code, it is very important to keep track of the parentheses and to use correct syntax.
One such syntax mistake is made when programmers think that C++ syntax is the same as algebraic syntax.
This is \emph{not} the case in C++!
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x = (5)(pow(3, 3)); // Incorrect syntax!
\end{lstlisting}\end{minipage}
When the compiler sees this, it doesn't view it as multiplication, but instead as (according to a professional), ``function shenanigans.''
It is important to be explicit with mathematical symbols in C++.
So instead of the incorrect code above, use:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x = 5 * (pow (3, 3));
\end{lstlisting}\end{minipage}
As an example, we will use code to compute the distance between the two points $(4,4)$ and $(6, 10)$ on a plane.
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int x1, x2, y1, y2;
float dist;
x1 = 4;
y1 = 4;
x2 = 6;
y2 = 10;
dist = sqrt(pow (x2 - x1, 2) + pow (y2 - y1, 2));
cout << dist;
\end{lstlisting}\end{minipage}
Your final answer after the calculation is executed is roughly $6.342555$.
Without the help of the advanced arithmetic operations, getting to this result would be a difficult, long, drawn-out process.
\Code{pow} and \Code{sqrt} are handy functions that make life easier, all with the help of the \Code{<cmath>} library.
\LevelE{Modulo}
The modulo operator (the percent sign: \Code{\%}) finds the remainder, or what was left over from division.
This program uses the modulo operator to find all prime numbers (all the numbers that never have a remainder of 0 when divided by every number except 1 and itself) that can be held by an \Code{int}.
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
#include <iostream>
using namespace std;
int main()
{
int divby, remainder;
for (int test = 1; test < 2147483647; test++)
{
bool isprime = true;
for(divby = 2; divby < test; divby++)
{ // Store the remainder of testprime/divby
remainder = test % divby;
if (remainder == 0) // If the number is not prime
{
isprime = false;
break; // Leave the for loop
}
}
if (isprime) // If it passes the test, it is prime.
cout << " " << testprime; // Print the prime
}
return 0;
}
\end{lstlisting}\end{minipage}
\LevelD{Review Questions}
\begin{enumerate}
\item Which \Code{\#include} library is needed to use advance arithmetic operators?
\item Write C++ code to calculate $2^9$.
\item Write a statement to set the value of a variable of type \Code{double} to the square root of 10001.
\item Complete the code below to find the length of the hypotenuse of a right triangle (remember that $a^2 + b^2 = c^2$) given the lengths of the other two sides. What is the final output of your code? \nopagebreak[4]
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
#include <iostream>
// Add necessary libraries here
using namespace std;
int main()
{
double a = 3.0, b = 4.0;
double c;
//
// Finish the program...
//
cout << "The hypotenuse of the right triangle is "
<< c << endl;
}
\end{lstlisting}\end{minipage}
\end{enumerate}
\LevelD{Review Answers}
\begin{enumerate}
\item \Code{\#include <cmath>} must be included to include advanced operators.
\item \Code{pow(2, 9)}
\item \Code{double b = sqrt(10001);}
\item
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float a = 3.0, b = 4.0;
double c;
a = pow(a, 2);
b = pow(b, 2);
c = sqrt(a+b);
cout << "The hypotenuse of the right triangle is "
<< c << endl;
}
\end{lstlisting}\end{minipage}
The final output of the code is:
\Code{The hypotenuse of the right triangle is 5.0}
\end{enumerate}
\LevelD{Further Reading}
\begin{itemize}
\item \url{http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/08-Arithmetic.pdf}
\item \url{http://www.cplusplus.com/reference/cmath/}
\end{itemize}