Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

Diffcrcncc cquation for nandom numbcrs. Simple random number generators are based on simulating difference equations. Here is a typical set of two equations: $$ \begin{aligned} &x_{n}=\left(a x_{n-1}+c\right) \bmod m \\ &y_{n}=x_{n} / m \end{aligned} $$ for \(n=1,2, \ldots .\) A seed \(x_{0}\) must be given to start the sequence. The numbers \(y_{1}, y_{2}, \ldots\), represent the random numbers and \(x_{0}, x_{1}, \ldots\) are "help" numbers. Although \(y_{n}\) is completely deterministic from (8.14)(8.15), the sequence \(y_{n}\) appears random. The mathematical expression \(p\) mod \(q\) is coded as \(p \%\) q in Python. Use \(a=8121, c=28411\), and \(m=134456 .\) Solve the system \((8.14)-\) (8.15) in a function that generates and returns \(N\) random numbers. Make a histogram to examine the distribution of the numbers (the \(y_{n}\) numbers are randomly distributed if the histogram is approximately flat). Name of program file: diffeq_random.py.

Short Answer

Expert verified
Implement a Python function to generate random numbers using the equations and plot their distribution with a histogram.

Step by step solution

01

Understand the Given Equations

The given difference equations are used to generate random numbers. The first equation updates a variable \(x_n\) based on its previous value \(x_{n-1}\), constants \(a\), \(c\), and modulus \(m\). The result is then taken modulo \(m\). In the second equation, \(y_n\) is computed as the normalized value by dividing \(x_n\) by \(m\). This results in a number between 0 and 1.
02

Implement the Random Number Generator

Create a function in Python, `generate_random_numbers`, that implements these equations to generate \(N\) random numbers. Use the formula: `x_n = (a * x_(n-1) + c) % m` and `y_n = x_n / m` in a loop to generate multiple random numbers, using a seed \(x_0\) to start the sequence.
03

Define Constants and Initialize Variables

In your function, define the constants \(a = 8121\), \(c = 28411\), and \(m = 134456\). Choose a seed value \(x_0\), such as 1 or any other positive integer. Initialize a list to store the \(y_n\) values.
04

Generate the Sequence

Use a loop that iterates from 1 to \(N\) to generate the sequence of numbers. For each \(n\), compute the next \(x_n\) using the modular arithmetic step, then compute \(y_n = x_n / m\), and store \(y_n\) in the list.
05

Plot the Histogram

Use a plotting library, such as Matplotlib, to create a histogram of the \(y_n\) values. Check if the distribution is approximately flat, indicating that the numbers are randomly distributed. Use `plt.hist(y_n_list)` to plot the histogram.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

Difference Equations
Difference equations are mathematical formulas that show how a quantity changes from one step to the next. They are often used to model dynamical systems and generate sequences of numbers. In the context of random number generation, the equations define the relationship between a generated number and the one preceding it.

For the given problem, we have two key equations. The first one updates a value called \(x_n\) using the previous value \(x_{n-1}\), two constants \(a\) and \(c\), and a modulus \(m\). Each new value of \(x_n\) is determined by the formula:
  • \(x_n = (a \times x_{n-1} + c) \mod m\)

The second equation normalizes \(x_n\) by dividing by \(m\), which results in \(y_n\):
  • \(y_n = x_n / m\)

This generates a number between 0 and 1, producing a sequence that appears random. To begin the generation, a starting point \(x_0\), known as the seed, must be defined.
Modular Arithmetic
Modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" upon reaching a certain value, called the modulus. It’s a concept often described as the arithmetic of clocks, providing a remainder after division of one number by another.

In the random number generation algorithm, modular arithmetic is used in the equation \(x_n = (a \times x_{n-1} + c) \mod m\). This mathematical step ensures that the number \(x_n\) does not exceed a maximum value \(m\).
  • "845 mod 12 = 5". This means when 845 is divided by 12, the remainder is 5.
  • In Python, the modulo operation is performed using the % operator, as in: "p % q"

This technique is crucial in generating pseudo-random numbers, creating sequences that do not immediately repeat and satisfying randomness over finite sequences.
Python Programming
Python is a popular programming language for implementing algorithms due to its simplicity and readability. When simulating random number generation with Python, we define a function to compute the sequence based on given difference equations.

To begin the task:
  • Define constants for the values \(a = 8121\), \(c = 28411\), and \(m = 134456\).
  • Choose an initial seed \(x_0\), for example, 1.
  • Implement a loop to calculate each \(x_n\) and \(y_n\).

Here is a simplified Python function outline:```python def generate_random_numbers(seed, N): x = seed y_values = [] for _ in range(N): x = (8121 * x + 28411) % 134456 y = x / 134456 y_values.append(y) return y_values```This snippet initializes a sequence and iteratively applies the difference equation to calculate new values.
Data Visualization
Data visualization is an essential aspect of understanding numeric data. It allows us to see patterns and distributions that might not be apparent at first glance.

In the context of random number generation, visualizing the output with a histogram helps determine if the sequence is well-distributed. A flat histogram suggests a uniform distribution, ideal for random numbers.
  • Use Matplotlib, a Python plotting library, for creating histograms.
  • Import the library using `import matplotlib.pyplot as plt`.
  • Plot the random number sequence with `plt.hist(y_values)`, where `y_values` is the list of numbers generated.
  • Adjust the number of bins in the histogram to see different levels of detail.

Visualization helps validate if the generated numbers seem random, thus confirming the effectiveness of the difference equations in simulating randomness.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

Simulate stock prices. A common mathematical model for the evolution of stock prices can be formulated as a difference equation $$ x_{n}=x_{n-1}+\Delta t \mu x_{n-1}+\sigma x_{n-1} \sqrt{\Delta t} r_{n-1} $$ where \(x_{n}\) is the stock price at time \(t_{n}, \Delta t\) is the time interval between two time levels \(\left(\Delta t=t_{n}-t_{n-1}\right), \mu\) is the growth rate of the stock price, \(\sigma\) is the volatility of the stock price, and \(r_{0}, \ldots, r_{n-1}\) are normally distributed random numbers with mean zero and unit standard deviation. An initial stock price \(x_{0}\) must be prescribed together with the input data \(\mu, \sigma\), and \(\Delta t\). We can make a remark that Equation (8.16) is a Forward Euler discretization of a stochastic differential equation for \(x(t)\) $$ \frac{d x}{d t}=\mu x+\sigma N(t) $$ where \(N(t)\) is a so-called white noise random time series signal. Such equations play a central role in modeling of stock prices. Make \(R\) realizations of \((8.16)\) for \(n=0, \ldots, N\) for \(N=5000\) steps over a time period of \(T=180\) days with a step size \(\Delta t=T / N\). Name of program file: stock_prices.py.

Throw dice and compute a small probability. Compute the probability of getting 6 eyes on all dice when rolling 7 dice. Since you need a large number of experiments in this case (see the first paragraph of Chapter 8.3), you can save quite some simulation time by using a vectorized implementation. Name of program file: roll_7dice.py.

Estimate the probability in a dice game. Make a program for estimating the probability of getting at least one 6 when throwing \(n\) dice. Read \(n\) and the number of experiments from the command line. (To verify the program, you can compare the estimated probability with the exact result \(11 / 36\) when \(n=2\).) Name of program file: one6_ndice.py.

Muke u cluss fur \(2 D\) nutuluwr wulk. The purpose of this exercise is to reimplement the ualk2D. py program from Chapter \(8.7 .1\) with the aid of classes. Make a class Particle with the coordinates \((x, y)\) and the time step number of a particle as attributes. A method move moves the particle in one of the four directions and updates the \((x, y)\) coordinates. Another class, Particles, holds a list of Particle objects and a plotstep parameter (as in walk2D.py). A method move moves all the particles one step, a method plot can make a plot of all particles, while a method moves performes a loop over time steps and calls move and plot in each step. Equip the Particle and Particles classes with print functionality such that one can print out all particles in a nice way by saying print \(\mathrm{P}\) (for a Particles instance \(\mathrm{p}\) ) or print self (inside a method). Hint: In _str_-, apply the pformat function from the pprint module to the list of particles, and make sure that__repr__ just reuse __str__ in both classes. To verify the implementation, print the first three positions of four particles in the walk2D. py program and compare with the corresponding results produced by the class-based implementation (the seed of the random number generator must of course be fixed identically in the two programs). You can just perform p.move() and print p three times in a verify function to do this verification task. Organize the complete code as a module such that the classes Particle and Particles can be reused in other programs. The test block should call a run(N) method to run the walk for \(N\) steps, where \(N\) is given on the command line. Compare the efficiency of the class version against the vectorized version in ualk2Dv.py, using the techniques of Appendix G.6.1. Name of program file: walk2Dc.py.

Compute a probability. What is the probability of getting a number between \(0.5\) and \(0.6\) when drawing uniformly distributed random numbers from the interval \([0,1)\) ? To answer this question empirically, let a program draw \(N\) such random numbers using Python's standard random module, count how many of them, \(M\), that fall in the interval \((0.5,0.6)\), and compute the probability as \(M / N\). Run the program with the four values \(N=10^{i}\) for \(i=1,2,3,6\). Name of program file: compute_prob.py.

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free