Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

BES 043: Computer Fundamentals and Programming

Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

Lesson title: Random Numbers & Math Library Materials:


Lesson Objectives: At the end of the lesson the students Computer, C++ Compiler
will be able to References:
1. Convert algebraic expression into C++ arithmetic Fundamentals of Programming C++ by
expression. Richard L. Halterman School of Computing
2. Write an algorithm for the application of the random Southern Adventist University 2018
number generation. http://www.cplusplus.com/reference/iomanip/
http://www.cplusplus.com/reference/cmath/

Productivity Tip: Try playing some music while doing the exercises on this module.

A. LESSON PREVIEW/REVIEW
1) Introduction (2 mins)
Topic: Random Numbers and Math Library functions
Lesson connection and relevance to the students: One thing that makes programming easy is by
using a ready-made sub-program (C++ call it functions, methods, or objects) already available as part of
a shared library (another term that refers to the header file, such as the iostream.h, iomanip.h, & string.h).
A Header file may contain special functions that will do some special task or processing for your program.
Most of the library is already a part of the package of a programming compiler. Some are shared by other
programmers, which can be downloaded from the internet for free!
If you are into a computer-related courses, another programming subject titled Object-Oriented
offers you to learn to create your own header file with functions necessary for your program that might
not be available in the internet.
Since there are ready-made special sub-programs, all we have to do is to try, understand, and
observe how it works. In programming, there’s no harm in trying, except if you’re creating a computer
virus.
Learning targets: Random number generation, pow(), sqrt()
2) Activity 1: What I Know Chart, part 1 (3 mins)
Write in the first column what you know about the given questions in the second column below.
The third column is left blank at this time.

What I Know Questions: What I Learned (Activity 4)


1. Are Math equations the same
as C++ Math equations?

2. Can a computer program limit


decimal places and round of
fractional numbers correctly?

3. Math computations in
computers are limited, true or
false?

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

B. MAIN LESSON
1) Activity 2: Content Notes (13 mins)
Random Numbers
Some applications require behavior that appears random. Random numbers are useful
particularly in games and simulations. For example, many board games use a die (one of a pair
of dice) to determine how many places a player is to advance. A die or pair of dice are used in
other games of chance. A die is a cube containing spots on each of its six faces. The number of
spots range from one to six. A player rolls a die or sometimes a pair of dice, and the side(s) that face up have
meaning in the game being played. The value of a face after a roll is determined at random by the complex
tumbling of the die. A software adaptation of a game that involves dice would need a way to simulate the random
roll of a die.
All algorithmic random number generators actually produce pseudorandom numbers, not true random
numbers. A pseudorandom number generator has a particular period, based on the nature of the algorithm used.
If the generator is used long enough, the pattern of numbers produced repeats itself exactly. A sequence of true
random numbers would not contain such a repeating subsequence. The good news is that all practical
algorithmic pseudorandom number generators have periods that are large enough for most applications.
C++ programmers can use two standard C functions for generating pseudorandom numbers: srand and rand:
void srand(unsigned)
int rand()
srand establishes the first value in the sequence of pseudorandom
integer values. Each call to rand returns the next value in the sequence of
pseudorandom values. Listing 8.10 (simplerandom.cpp) shows how a
sequence of 100 pseudorandom numbers can be printed.
The numbers printed by the program appear to be random. The
algorithm is given a seed value to begin, and a formula is used to produce
the next value. The seed value determines the sequence of numbers
generated; identical seed values generate identical sequences. If you run
the program again, the same sequence is displayed because the same seed
value, 23, is used. In order to allow each program run to display different
sequences, the seed value must be different for each run. How can we
establish a different seed value for each run? The best way to make up a “random” seed at run time is to use
the time function which is found in the ctime library. The call time(0) returns the number of seconds since midnight
January 1, 1970.
This value obviously differs between program runs, so each execution will use a different seed value, and
the generated pseudorandom number sequences will be different. Listing 8.11 (betterrandom.cpp) incorporates
the time function to improve its randomness over multiple executions.

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

Each execution of Listing 8.11 (betterrandom.cpp) produces a


different pseudorandom number sequence. The actual type of value
that time returns is time_t, so the result from a call to time must be cast
to unsigned int before being used with srand.
Notice that the numbers returned by rand can be rather large.
The pseudorandom values range from 0 to a maximum value that is
implementation dependent. The maximum value for Visual C++s´ rand
function is 32,767, which corresponds to the largest 16-bit signed int
value. The cstdlib header defines the constant RAND_MAX that
represents the largest value in the range. The following statement
cout << RAND_MAX << '\n';
would print the value of RAND_MAX for a particular system.
Ordinarily we need values in a more limited range, like 1. 100. Simple arithmetic with the modulus operator
can produce the result we need. If n is any nonnegative integer and m is any positive integer, the expression
n%m
produces a value in the range 0. m−1.
This means the statement
int r = rand() % 100;
can assign only values in the range 0...99 to r. If we really want values in the range 1. 100, what can we do?
We simply need only add one to the result:
int r = rand() % 100 + 1;
This statement produces pseudorandom numbers in the range 1. 100.
We now have all we need to write a program that simulates the rolling of a die.

Math Header File


Header <cmath> or <math.h> declares a set of functions to compute common mathematical operations
and transformations: (A complete list of the numeric functions available to C++ can be found at
http://www.cplusplus. com/reference/clibrary/cmath/)
Trigonometric functions
cos Compute cosine
sin Compute sine
tan Compute tangent
acos Compute arc cosine
asin Compute arc sine
atan Compute arc tangent
atan2 Compute arc tangent with two parameters

Hyperbolic functions
cosh Compute hyperbolic cosine
sinh Compute hyperbolic sine
tanh Compute hyperbolic tangent
acosh Compute arc hyperbolic cosine
asinh Compute arc hyperbolic sine
atanh Compute arc hyperbolic tangent

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

Exponential and logarithmic functions


exp Compute exponential function
frexp Get significand and exponent
ldexp Generate value from significand and exponent
log Compute natural logarithm
log10 Compute common logarithm
modf Break into fractional and integral parts
exp2 Compute binary exponential function
expm1 Compute exponential minus one
ilogb Integer binary logarithm
log1p Compute logarithm plus one
log2 Compute binary logarithm
logb Compute floating-point base logarithm
scalbn Scale significand using floating-point base exponent
scalbln Scale significand using floating-point base exponent (long)

Power functions
pow Raise to power
sqrt Compute square root
cbrt Compute cubic root
hypot Compute hypotenuse

Here are some programs on how to use them:

 #include <math.h>
This header file contains the sqrt() function. It is to be included with a .h extension. The C++ compiler
cannot locate the said file during compilation process without the extension. It seems that there’s still
inconsistency with how the compiler deals with header files. For this simple program that involves simple
cout and sqrt() only, all the declarations above the main program can be re-written as
/* sqrt example */
#include <iostream.h> // cout
#include <math.h> // sqrt
void main ()
{
The using namespace std; can still be removed
because there’s no string variables and a string.h is
involved in the program but a .h extension has to be
written with the iostream header file.
 result = sqrt (x);
The sqrt() functions the same as the standard math √ (square root). It gives the square root of any number
placed as its parameter (enclosed with a pair of parentheses on the right side of the sgrt name). For this
statement, it gives or returns the square root of any value of the variable x. The sqrt() function takes only
one parameter, it can be an integer, double or any valid C++ math expression, such as x + 2. A negative
x will result to an indefinite value.

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

 pow (3, 2)
Since we cannot write the number with a superscript (32) in the C++ compiler, we may use the ^ character
to represent it as 3^2 for displaying, where the base number 3 is raised to the power 2.
The Listing 5.5 program will display

The pow() is available in the math.h library. It takes two parameters –


(the base number, & the exponent). Both parameter value can be an
integer, double or any valid C++ math expression.

2) Activity 3: Skill-building Activities (with answer key) (18 mins + 2 mins checking)
Write an algorithm for a program that will let a user guess some magic number. Before the program ask
a number, it will set a number randomly chosen from the range of 1 to 9 and call it the magic number. If
the entered number is lower or higher than the magic number, it will prompt the user if it should be lower
or higher than the entered number. The program will only stop if the magic number has been identified.

3) Activity 4: What I Know Chart, part 2 (2 mins)


{This serves as the student’s review and summary of what was learned from the session.}
Monitor how your knowledge has changed by reviewing the questions in the What I Know Chart from
Activity 1 and write your answers to the questions based on what you now know in the third column of
the chart.

4) Activity 5: Check for Understanding (5 mins)


Trace the output for the following:
1. int i = 16; cout << sqrt(i) << '\n';
2. double a = 5, b = 3; cout << pow(a, b) << '\n';

Convert the following Mathematical expression into C++ arithmetic expression:

Algebraic Expressions C++ Expressions


1. a = √(b^2 + c^2))

2. Area = π(r2)

3.

4.

C. LESSON WRAP-UP
1) Activity 6: Thinking about Learning (5 mins)

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #15

Name: Class number:


Section: Schedule: Date:

Mark the place in the work tracker which is simply a visual to help you track how much work you have
accomplished and how much work there is left to do. This tracker will be part of your activity sheet.

To develop habits on thinking about learning, answer the questions below about your learning
experience.
Three things you learned:
1.
2.
3.

Two things that you’d like to learn more about:


1.
2.

One question you still have:


1.
FAQs
1.) What Math equation or computation that a computer program cannot do or solve? Answer: So far, all
Math equations can also be applied using a computer by creating a program for it. In fact, we already
have a Mathematical equation simulator software, for example: MathLab software.

2.) How do we know on how to use all of those Math functions in a program? Answer: We can know how to
use any of those Math functions by referring to a programming book or manual or the easiest way is to
use the internet. You can find a lot of C++ programming tutorial website for free. Example:
www.cplusplus.com

This document is the property of PHINMA EDUCATION

You might also like