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...
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,...
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...
Build a Dynamic Programming algorithm in Python for the following problem. Given two sequences of vowels,...
Build a Dynamic Programming algorithm in Python for the following problem. Given two sequences of vowels, find the length of longest subsequence present in both of them. NOTE: A subsequence is a sequence that appears in the same order, but not necessarily contiguous. For example, “aei”, “aeo”, “eio”, “aiu”, ... are subsequences of “aeiou”. Sample Input 1: aeiou aiu Sample Output 1: 3 Sample Input 2: aeaiueoiuaeeoeooaauoi aeuioauuuoaeieeaueuiouaiieuiuuuaoueueauaeiauuo Sample Output 2: 16 Sample Input 3: iioioieiaiauaoeoiioiiue iuuueauiaieooaoaaouaaaae Sample Output 3:...
DIRECTIONS: Complete the following Programming Exercise in Python. Name the file Lastname_Firstname_E1. You just started your...
DIRECTIONS: Complete the following Programming Exercise in Python. Name the file Lastname_Firstname_E1. You just started your summer internship with ImmunityPlus based in La Crosse, Wisconsin. You are working with the forecasting team to estimate how many doses of an immunization drug will be needed. For each drug estimation, you will be provided the following information: corona.txt 39 20 31 10 42 49 54 21 70 40 47 60 - The size of the target population. - The life expectancy, in...
Formulate but do not solve the following exercise as a linear programming problem. Kane Manufacturing has...
Formulate but do not solve the following exercise as a linear programming problem. Kane Manufacturing has a division that produces two models of fireplace grates, x units of model A and y units of model B. To produce each model A requires 2 lb of cast iron and 8 min of labor. To produce each model B grate requires 5 lb of cast iron and 5 min of labor. The profit for each model A grate is $2.50, and the...
This problem is adapted from an earlier edition of P&H. Consider the following code used to...
This problem is adapted from an earlier edition of P&H. Consider the following code used to implement the instruction: foo $s0,$s1,$s2 mask: .word 0xFFFFF83F start: la $t0,mask lw $t0,0($t0) la $s0,shftr lw $s0,0($s0) and $s0,$s0,$t0 andi $s2,$s2,0x1f sll $s2,$s2,6 or $s0,$s0,$s2 la $t5,shftr sw $s0,0($t5) shftr: sll $s0,$s1,0 Add meaningful comments to the code. Please explain each line and write a paragraph describing how it works. Why do you suppose that writing “self-modifying code” such as this is a bad...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT