Question

In: Computer Science

This problem is adapted from Exercise 37 of Langtangen’s “A Primer on Scientific Programming with Python”....

This problem is adapted from Exercise 37 of Langtangen’s “A Primer on Scientific Programming with Python”.

Simulating gas particles in a closed space is something you can do with a Monte Carlo type simulation – simulate a period of time (using a loop) and “move” particles around (change values for (x,y) coordinates) for each unit of time. This kind of simulation is called a “random walk”.

Download the file randomwalk.py(i posted it below). This implements a Monte Carlo simulation for a random 2-dimensional walk. It uses numpy arrays, but it does not use them idiomatically.

Your task for this exercise is to change this program to use numpy arrays idiomatically. That is, the block

for i in range(np):
    direction = random.randint(1, 4)
    if direction == NORTH:
        ypositions[i] += 1
    elif direction == SOUTH:
        ypositions[i] -= 1
    elif direction == EAST:
        xpositions[i] += 1
    elif direction == WEST:
        xpositions[i] -= 1

should be rewritten to use numpy arrays of random integers.

Below is randomwalk.py

import random
random.seed(10122019)
import numpy
import matplotlib.pyplot as plt

def random_walk_2D(np, ns):
# xpositions = numpy.zeros(size=np) #### part 1
# ypositions = numpy.zeros(size=np)
positions = numpy.zeros(size=(np, 2)) #### part 2
# extent of the axis in the plot:
xymax = 3*numpy.sqrt(ns); xymin = -xymax

for _ in range(ns):
for i in range(np):
direction = random.randint(1, 4)
if direction == NORTH:
ypositions[i] += 1
elif direction == SOUTH:
ypositions[i] -= 1
elif direction == EAST:
xpositions[i] += 1
elif direction == WEST:
xpositions[i] -= 1
# xpositions += numpy.random.randint(-1, 2, size=np) #### part 1
# ypositions += numpy.random.randint(-1, 2, size=np) #### part 1
positions += numpy.random.randint(-1, 2, size=(np, 2)) #### part 2

# plt.plot(xpositions, ypositions, 'ko') #### part 1
plt.plot(positions[:,0], positions[:,1], 'ko') #### part2
plt.axis([xymin, xymax, xymin, xymax])
plt.title('{particles} particles after {steps} steps'.format(particles=np, steps=ns))
plt.savefig('tmp_{steps}.pdf'.format(steps=ns))
  
return positions[:,0], positions[:,1]

np = 100 # number of particles
ns = 100 # number of steps
x, y = random_walk_2D(np, ns)

Solutions

Expert Solution

ANSWER:

  • I have provided the properly commented code in both text and image format so you can easily copy the code as well as check for correct indentation.
  • I have provided the output image of the code so you can easily cross-check for the correct output of the code.
  • Have a nice and healthy day!!

CODE TEXT

#Below is randomwalk.py
import numpy
# seeding random of numpy
numpy.random.seed(10122019)
import matplotlib.pyplot as plt

def random_walk_2D(np, ns):
# xpositions = numpy.zeros(size=np) #### part 1
# ypositions = numpy.zeros(size=np)
positions = numpy.zeros(shape=(np, 2)) #### part 2
# extent of the axis in the plot:
xymax = 3*numpy.sqrt(ns); xymin = -xymax
  
for _ in range(ns):
# need random array of 1 and -1 and not 0, because moment of particle
# in each step is compullsory
# step 1. fetching random array of 1 and 0, of size npx2
random_array = numpy.random.randint(0, 2, size=(np, 2))
# step 2. converting 0's to -1
# using numpy.where to find 0's and replacing them with -1
con_array=numpy.where(random_array==0,-1,random_array)
  
# adding the con_array to positions array to modify positions for this step
positions += con_array

# plt.plot(xpositions, ypositions, 'ko') #### part 1
plt.plot(positions[:,0], positions[:,1], 'ko') #### part2
plt.axis([xymin, xymax, xymin, xymax])
plt.title('{particles} particles after {steps} steps'.format(particles=np, steps=ns))
plt.savefig('tmp_{steps}.pdf'.format(steps=ns))
  
return positions[:,0], positions[:,1]

np = 100 # number of particles
ns = 100 # number of steps
x, y = random_walk_2D(np, ns)

CODE IMAGE

OUTPUT IMAGE


Related Solutions

This is an exercise to design and write a Python program in good programming style for...
This is an exercise to design and write a Python program in good programming style for a simulation of stock price over a period of 100 days. In this exercise, you are asked to simulate the stock price starting at $100.00 for 100 days with a daily fluctuation based on the Normal Distribution with mean = 0.0 & sigma = 0.0125. The program will show the daily stock price, the 7-day minimum, the 7-day maximum, the 7-day average, and the...
Chapter 7, Problem 3PE from Introduction to Programming using Python by Y. Daniel Liang. Problem (The...
Chapter 7, Problem 3PE from Introduction to Programming using Python by Y. Daniel Liang. Problem (The Account class) Design a class named Account that contains: ■ A private int data field named id for the account. ■ A private float data field named balance for the account. ■ A private float data field named annualInterestRate that stores the current interest rate. ■ A constructor that creates an account with the specified id (default 0), initial balance (default 100), and annual...
Python programming problem! Suppose that there is a json file called data from the desktop. I...
Python programming problem! Suppose that there is a json file called data from the desktop. I want to print the value with the key of "year" and "country". Json file below: { "A":{ "year":11, "grade":A, "country":America}, "B":{ "year":18, "grade":C, "country":England}, "C":{ "year":19, "grade":B, "country":China},} I want a code that I can only replace the name of key from year to grade and the code could be work.
2. Adapted from Exercise 3.19 in the textbook. The length of human pregnancies from conception to...
2. Adapted from Exercise 3.19 in the textbook. The length of human pregnancies from conception to birth varies according to a distribution that is approximately normal with mean 266 days and standard deviation 16 days. (a) Between what range of days do about 95% of pregnancies last? (b) What proportion of pregnancies last more than 170 days? (c) What proportion of pregnancies last less than 245 days? 1 (d) What proportion of pregnancies last between 245 and 280 days? (e)...
Modified from Chapter 07 Programming Exercise 5 Original Exercise: Rock, Paper, Scissors Modification Programming Exercise 11...
Modified from Chapter 07 Programming Exercise 5 Original Exercise: Rock, Paper, Scissors Modification Programming Exercise 11 in Chapter 6 asked you to design a program that plays the Rock, Paper, Scissors game. In the program, the user enters one of the three strings—"rock", "paper", or "scissors"—at the keyboard. Add input validation (with a case-insensitive comparison) to make sure the user enters one of those strings only. Modifications: Allow the user to input "r", "p", "s" or the full strings "Rock",...
2. Problem 2 is adapted from the Problem 39 at the end of Chapter 11. Please...
2. Problem 2 is adapted from the Problem 39 at the end of Chapter 11. Please solve this problem in Excel and submit your Excel spreadsheet. The problem is as follows: The state of Virginia has implemented a Standard of Learning (SOL) test that all public school students must pass before they can graduate from high school. A passing grade is 75. Montgomery County High School administrators want to gauge how well their students might do on the SOL test,...
Python Programming Exercise Scenario: Write a program that asks the user to enter scores the number...
Python Programming Exercise Scenario: Write a program that asks the user to enter scores the number is based on what the user wants to enter. The program will display a letter grade and associated message for each score, based on the table below, and the average score. The program will not contain any repeated code and have a minimum of two functions besides Main. Score                Letter Grade             Message 90 – 100                       A                     Excellent work 89 – 80                         B                     Nice job 79 –...
1. Adapted from Exercise 3.32 in the textbook. A large group of male runners walk on...
1. Adapted from Exercise 3.32 in the textbook. A large group of male runners walk on treadmill for 6 minutes. Their heart rates in beats per minute at the end vary from runner to runner according to the N(104, 12.5) distribution. The heart rate for male non-runners after the same exercise have the N(130, 17) distribution. (a) What percent of runners have heart rates above 135? What percent of non-runners have heart rates above 135? (b) What is the median...
MUST BE PYTHON 3 Instructions: The following programming problem can be solved by a program that...
MUST BE PYTHON 3 Instructions: The following programming problem can be solved by a program that performs three basic tasks (Input Data, Process Data, Output Results) along with selection and repetition coding techniques. Problem Statement A finance company provides loans for motorcycles at different rates depending on how much the total loan amount is and how many payments will be made on the loan. Using the information in the table below, write a program that will calculate the monthly payment...
Textbook: Starting out with Python (3rd or 4the Edition) Question: Programming Exercise # 9 - Trivia...
Textbook: Starting out with Python (3rd or 4the Edition) Question: Programming Exercise # 9 - Trivia Question In this programming exercise, you will create a simple trivia game for two players. The program will work like this: Starting with player 1, each player gets a turn at answering 5 trivia questions. (There should be a total of 10 questions.) When a question is displayed, 4 possible answers are also displayed. Only one of the answers is correct, and if the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT