Nothing Special   »   [go: up one dir, main page]

CSCI 1120: Introduction To Computing Using C++ Tutorial 6: Predefined Function

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

CSCI 1120

Introduction to Computing Using C++


Tutorial 6: Predefined Function

20th Oct. 2020


Predefined Functions
• Review about functions
• C++ Standard Libraries
• Calling predefined functions
• Math library function examples
• Random number generation

2
Functions: Function Prototypes
• Function prototype consists of
• Function name
• Parameters
• Information the function takes in
• C++ is “strong typed” – error to pass a parameter of the wrong type
• Return type
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing
• Only needed if function definition comes after the function call in the
program

3
Functions: Header Files
• Header files
– Contain function prototypes for library functions
– <cstdlib> , <cmath>, etc.
– Load with #include <filename>
• Example:
#include <cmath>
• Custom header files
– Defined by the programmer
– Save as filename.h
– Loaded into program using
#include "filename.h"

4
C++ Standard Libraries
• C++ provides a huge set of libraries:
– Standard ANSI C library ported over to C++. These libraries are name with a prefix "c" and
without the ".h", e.g., <cmath> for C's <math.h>, <cstdlib> for C's <stdlib.h>, etc
– C++ new Libraries, such as <iostream>, <iomanip>, <string>, <fstream>, <sstream>.
– C++ Standard Template Library (STL): consists of containers, iterators, algorithms and function
objects.
– Boost C++ libraries.

5
Calling Predefined Functions
• To call a function, you have to know the following info about the
function (usually from manuals)
• name, functionality, parameters, return value

• You may also need to know which header file(s) to include


• e.g.: To use math functions, you have to include "cmath" as
#include <cmath>

• Optionally, you may need to find out


• What namespace to use
• Which "library file" to add to your project (for non-standard C++ functions)

6
Math Library Functions
• Math library functions
– Allow the programmer to perform common mathematical calculations
– Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)
• Example
cout << sqrt( 900.0 );
– Calls the sqrt (square root) function. The preceding statement would print 30
– The sqrt function takes an argument of type double and returns a result of
type double, as do all functions in the math library

7
Math Function Examples
1 #include <iostream>
2 #include <cmath> // Need this line to use math functions
3 using namespace std;
4 You can store the returned value
5 int main() { in a variable or use the returned
6 double x; value directly in an expression.
7 x = sqrt(10);
8
9 cout << "x = square root of 10 = " << x << endl;
10 cout << "Ceiling of x = " << ceil(x) << endl;
11 cout << "2 to the power x = " << pow(2.0, x) << endl;
12 cout << "log(x + 10) = " << log10(x + 10) << endl;
13 x = square root of 10 = 3.16228
14 return 0; Ceiling of x = 4
15 } 2 to the power x = 8.95242
8
log(x + 10) = 1.11933
Functions Description Examples

ceil( x ) rounds x to the smallest integer ceil(9.2) is 10.0


not less than x ceil(-9.8) is -9.0
⌈x⌉
floor ( x ) rounds x to the largest integer not floor(9.2) is 9.0
greater than x floor(-9.8) is -10.0
⌊x⌋
exp( x ) exponential function exp(1.0) is 2.71828
ex
fabs( x ) absolute value of x fabs(5.1) is 5.1
|x| fabs(0.0) is 0.0
fabs(-8.76) is 8.76
pow( x, y ) x raised to power y pow(2, 7) is 128.0
xy pow(9, .5) is 3.0

sqrt( x ) square root of x sqrt(900.0) is 30.0


√x sqrt(9.0) is 3.0

9
Functions Description Examples

log ( x ) natural logarithm of x (base e) log(2.718282) ≈ 1.0


loge x or ln x log(exp(3.0)) is 3.0
ln e = 1
ln ex = x * ln e = x
log10 ( x ) logarithm of x (base 10) log(10.0) is 1.0
log10 x log(100.0) is 2.0

sin( x ) trigonometric sine, cosine and sin(0.0) is 0.0


cos( x ) tangent of x (x in radians) cos(0.0) is 1.0
tan( x ) sin x tan(0.0) is 0.0
cos x
tan x Let pi = 3.141592654
90° = π/ 2 sin(pi / 2) ≈ 1.0
180° = π cos(pi / 2) ≈ 0.0
270° = 3 * π / 4 tan(pi / 2) ≈ a large #

Ref: http://www.cplusplus.com/reference/cmath/ 10
Random Number Generation
• rand function
i = rand();
– Load <cstdlib>
– Generates a pseudorandom number between 0 and RAND_MAX (usually 32767)
• A pseudorandom number is a preset sequence of "random" numbers
• The same sequence is generated upon every program execution
• srand function
– Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <ctime>
– time( 0 )
• The time at which the program was compiled
– Changes the seed every time the program is compiled, thereby allowing rand to
generate random numbers
11
Random Number Generation
• rand() (#include <cstdlib>)
x = rand();
• x is assigned an integer between 0 and RAND_MAX (usually 32767)

• Scaling and shifting


rand() % range
• Generates a random number in the interval [0, range – 1]
• e.g.: x = rand() % 100; // x in [0, 99]

start + rand() % (end - start + 1)


• Generates a random number in the interval [start, end]
• e.g.: x = 10 + rand() % 8 // x in [10, 17]

12
Sample Problem – Distribution of rand()

• Use rand() to simulate the process of throwing a dice for 6000


times

• Calculate the number of times each dice number appears in the


simulation.
• What outcome do you expect?

13
1 #include <iostream>
2 using namespace std;
3 #include <iomanip> // Needed by setw()
4 #include <cstdlib>
5
6 int main() {
7
8 // # of times the outcome is 1, 2, 3, 4, 5, or 6
9 int freq1 = 0, freq2 = 0, freq3 = 0,
10 freq4 = 0, freq5 = 0, freq6 = 0;
11
12 int face; // face value of the dice
13 int i = 1;
14
15 while (i <= 6000) {
16 face = 1 + rand() % 6;
17
18
14
19 if (face == 1) freq1++;
Reserve 13 spaces for
20 else if (face == 2) freq2++;
the next output.
21 else if (face == 3) freq3++;
22 else if (face == 4) freq4++; The output is right
23 else if (face == 5) freq5++; justified in the reserved
24 else freq6++; space.
25 No use if next output is
26 i++; too big to fit into the
27 } // End of while loop reserved space.
28
29 cout << "Face" << setw(13) << "Frequency\n"
30 << " 1" << setw(13) << freq1 << endl
31 << " 2" << setw(13) << freq2 << endl
32 << " 3" << setw(13) << freq3 << endl
33 << " 4" << setw(13) << freq4 << endl
34 << " 5" << setw(13) << freq5 << endl
35 << " 6" << setw(13) << freq6 << endl;
36
37 return 0;
38 }
39 15
Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999

13 character-wide

16
srand() and Random Number Sequence
• rand() only generates pseudorandom number
sequence.

• A seed value controls what sequence of numbers to be


generated.

• To get different random sequences, call


srand(seed);
• seed is a non-negative integer number.
• Same seed  same sequence of random numbers
• Every call to srand() resets the random number
sequence
17
1 #include <iostream>
using namespace std;
2
#include <cstdlib>
3 #include <iomanip>
4 int main() {
5 unsigned int seed;
6 int i = 1;
7 cout << "Enter seed: ";
8 cin >> seed;
9 srand( seed ); // Initialize random number generator
10
11 while (i <= 10) {
cout << setw(10) << ( 1 + rand() % 6 );
12
13 // prints 5 #'s per line
14 if (i % 5 == 0)
15 cout << endl;
16 i++;
17 } // end of while
18 return 0;
19 }
18
Enter seed: 67
6 1 4 6 2
1 6 1 6 4

Enter seed: 432


4 6 3 1 6
3 1 5 4 2

Enter seed: 67
6 1 4 6 2
1 6 1 6 4

rand() yields the same


sequence of pseudorandom
numbers if it is initialized
with the same seed value.

19
macOS

Windows

With the same seed value, the


sequence of pseudorandom
numbers may not be the same
across different systems.
20
1 #include <iostream>
using namespace std; Use the current time to set the seed
2
#include <cstdlib>
3 #include <ctime> Need to include "ctime" as
4 #include <iomanip> #include <ctime>
5
6 int main() {
int i = 1; time(0)returns the current time in
7 seconds since 1st Jan 1970.
8 srand(time(0));
9
10 while (i <= 10) {
11 cout << setw(10) << ( 1 + rand() % 6 );
12 // prints 5 #'s per line
13 if (i % 5 == 0)
14 cout << endl; Advantage: No need to ask user for a
15 seed value
i++;
16 } // end of while
17 return 0;
18 }
19 21
The first output

Wait a “second” to get the second output

22
Example – randGenPuzzle() function in assignment 3

• Recall that we have provided a randGenPuzzle() function to you in


assignment 3, which can return a solvable 8-puzzle.

• The randGenPuzzle() makes use of rand() function to generate a


random 8-puzzle game.

23
Example – randGenPuzzle() function in assignment 3
Generate a random digit in the
range [0, 8].

while loop: generate each digit of p


one by one.
Example:
s=3, divm=1000, p=3, mask=1000,
divp=10.

s=4, divm=10000, p=43, mask=11000,


divp=100.

s=1, divm=10, p=143,mask=11010,


divp=1000.
…..

24
Sample Problem:

• Generate a random variable in [0,1]


x = (double)rand() / RAND_MAX
• Suppose there is a machine, which generates 3 with probability 0.2, 5
with probability 0.5, and 7 with probability 0.3. How to solve the
problem?

25
Sample Problem: code
int main() {
int i, a, b, c, k;
double x;
a = 0; b = 0; c = 0;
srand(time(NULL));
for (i = 1; i <= 10000; i ++){
x = (double)rand() / RAND_MAX; // generate random variable
if (x <= 0.2){
k = 3; a ++; // count the number of 3
}
if (x > 0.2 && x < 0.7){
k = 5; b ++; // count the number of 5
}
if (x >= 0.7){
k = 7; c ++; // count number of 7
}
}
cout<< a <<" "<< b << " " << c << endl;
return 0;
} 26
Sample Problem 2
• Generate a random permutation of the sequence (1, 2, …, n):

-- To shuffle an array a of n elements (indices 0..n-1):


for i from n−1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]

27
Sample Code
#include<iostream> // To shuffle an array a of n elements
#include<cstdlib> (indices 0..n-1):
using namespace std; for (int i = n - 1; i > 0; i--) {
int j = rand() % i;
void printArray(int x[], int n) { swap(randperm[j], randperm[i]);
for (int i = 0; i < n; i++) { }
cout << x[i] << " "; // print the random permuration sequence
} cout << "Random Permutation: ";
cout << endl; printArray(randperm, n);
}
return 0;
int main() { }
int n = 10;
int randperm[10]; // declare the array
// assign (0, 1, ..., n-1) to the array
for (int i = 0; i < n; i++) {
randperm[i] = i;
}
cout << "Original Array: ";
printArray(randperm, n);

28

You might also like