Week 10 - Gemini Flashcards
(23 cards)
What is the purpose of the rand()
function in C++, and what header file is needed to use it?
The rand()
function generates pseudo-random integers in the range from 0 to RAND_MAX
. The <cstdlib>
header file is needed.
What is RAND_MAX
?
RAND_MAX
is a constant defined in <cstdlib>
that represents the maximum value that can be returned by the rand()
function.
Why is it important to ‘seed’ a pseudo-random number generator, and how is this typically done in C++ using srand()
and time()
? Which headers are needed?
Seeding initializes the pseudo-random number generator to a starting point. Without seeding, or with the same seed, rand()
will produce the same sequence of numbers each time the program runs. Using srand((unsigned int)time(NULL));
(or srand(time(0));
) seeds the generator with the current time, leading to different sequences on different runs. Headers: <cstdlib>
for srand()
and <ctime>
for time()
.
How can you generate a pseudo-random integer k
that simulates a fair six-sided die roll (values 1 to 6) using rand()
?
int k = 1 + rand() % 6;
The rand() % 6
part gives a number from 0 to 5, so adding 1 shifts it to the range 1 to 6.
How can you generate a pseudo-random double-precision floating-point number r
approximately uniformly distributed in the range [0.0, 1.0)
using rand()
?
double r = static_cast<double>(rand()) / (RAND_MAX + 1.0);
Adding 1.0 to RAND_MAX
in the denominator helps ensure the result is strictly less than 1.0.
What is the purpose of the <fstream>
library in C++? Name the three main classes it provides for file operations.
The <fstream>
library provides classes for file input and output operations. The main classes are: ifstream
(for input from files), ofstream
(for output to files), and fstream
(for both input and output).
Explain the ios::app
file opening mode. What happens if the file exists? What if it doesn’t?
ios::app
(append mode) opens a file for output, and all write operations are appended to the end of the file. If the file does not exist, it is created. Existing content is preserved.
Explain the ios::ate
file opening mode.
ios::ate
(“at end”) opens a file and moves the read/write control (file pointer) to the end of the file immediately after opening. Data can be written anywhere, but it starts at the end. If the file doesn’t exist, it’s typically created.
Explain the ios::trunc
file opening mode. What happens if it’s used with ios::out
and the file already exists?
ios::trunc
(truncate mode). If the file exists, its contents are discarded (truncated to zero length) before opening. If used with ios::out
(which is often the default when ios::trunc
is implied), and the file exists, it will be emptied. If the file doesn’t exist, it’s created.
How can you check if a file was successfully opened using an fstream
, ifstream
, or ofstream
object (e.g., myFile
)?
You can check the state of the stream object in a boolean context: if (!myFile)
or if (myFile.fail())
indicates an error (e.g., file not opened). Alternatively, if (myFile.is_open())
checks if the file is successfully open.
When reading a file character by character, what is the role of the myFile.eof()
method?
myFile.eof()
(end-of-file) returns true
if a previous read operation attempted to read past the end of the file. It’s often used in a loop to determine when to stop reading, but it’s important to attempt a read before checking eof()
.
When designing a class that will store a collection of data of a generic type (e.g., a lattice that could hold doubles or bools), what C++ feature allows you to write the class definition once to support multiple data types?
Class Templates. Example: template <typename Type> class MyLattice { /* ... uses Type ... */ };
.
If a class template BinLattice<Type>
is defined, how would you instantiate one object to store double
values and another to store bool
values?
BinLattice<double> priceTree;
and BinLattice<bool> stoppingTree;
.
Why are the definitions of class templates (including member functions not defined inline) usually placed entirely within header files?
The compiler needs the complete template definition (not just declarations) to generate the specific class code when the template is instantiated with an actual type (e.g., BinLattice<double>
). If definitions were in a .cpp
file, they wouldn’t be visible during the compilation of other files using the template, leading to linker errors.
What is the purpose of std::vector<std::vector<double>> myGrid;
? How would you access an element, say at outer index r
and inner index c
?
This declares myGrid
as a vector where each element is itself a std::vector<double>
. It can be used to represent a 2D grid or a lattice. An element can be accessed using myGrid[r][c]
.
What does the .back()
member function of a std::vector
do?
It returns a reference to the last element in the vector. The vector must not be empty when calling .back()
.
In the context of designing a system with classes (e.g., a Model
class and a ComputationEngine
class), why is it beneficial to pass objects of these classes by const
reference (const Model& model
) to functions that only need to read their data?
Passing by const
reference avoids the overhead of making a full copy of the object (which can be expensive for complex objects) while also ensuring that the function cannot accidentally modify the original object’s state.
Conceptually, how can you simulate a sequence of events or values (like a price path) using random numbers and store them in a std::vector
?
Initialize the first value. Then, in a loop for the desired number of steps: generate a random number, apply a transformation rule (based on the random number and the previous value) to get the next value in the sequence, and store this new value in the std::vector
(e.g., using push_back()
).
What is the basic idea behind the Box-Muller algorithm for generating normally distributed random numbers? (Practical 7, Problem 3)
The Box-Muller algorithm transforms two independent uniformly distributed random numbers (typically in the range (0,1]) into two independent standard normally distributed random numbers (mean 0, variance 1) using formulas involving logarithms, square roots, sines, and cosines.
In a C++ context, if you need to estimate the derivative of a function f(x)
numerically using a central difference, what is the formula and how might it be implemented? (Practical 7, Problem 8)
Formula: $f’(x) \approx (f(x+h) - f(x-h)) / (2h)$ for a small h
. Implementation: Define a function that calculates f(x)
. Then, in another function, take x
and h
as input, call the f(x)
function for x+h
and x-h
, and apply the formula.
If you have a std::vector<double> data
, what are the basic steps to calculate its sample mean? (Practical 3-3, Problem 3.1 / Practical 7, Problem 9)
- Initialize a sum variable to 0.0. 2. Iterate through all elements in the vector, adding each element to the sum. 3. Divide the total sum by the number of elements (obtained via
data.size()
). Ensuredata.size()
is not zero to avoid division by zero.
If you have a std::vector<double> data
and its sample mean, what are the basic steps to calculate its sample standard deviation? (Practical 3-3, Problem 3.2 / Practical 7, Problem 9)
- For each element, calculate the squared difference between the element and the mean. 2. Sum these squared differences. 3. Divide this sum by
N
(for population-like SD) orN-1
(for sample SD, where N isdata.size()
). 4. Take the square root of the result.
What is ‘file handling’ in C++ primarily used for?
It’s used to store data from a program permanently in a storage device (like a hard drive) and to read previously stored data back into a program. This allows data to persist beyond the program’s execution.