0% found this document useful (0 votes)
6 views

Assignment2

The document contains a series of experiments conducted as part of an assignment for a Computer Simulation and Modeling course at Bangabandhu Sheikh Mujibur Rahman Science and Technology University. Each experiment explores different concepts such as sampling distribution, numerical integration using Monte Carlo methods, estimating π, simulating random walks, and weather forecasting using a Markov Chain model, with accompanying code and discussions on methodology and results. The experiments utilize Python programming and various libraries to visualize data and demonstrate statistical principles.

Uploaded by

Shohanur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Assignment2

The document contains a series of experiments conducted as part of an assignment for a Computer Simulation and Modeling course at Bangabandhu Sheikh Mujibur Rahman Science and Technology University. Each experiment explores different concepts such as sampling distribution, numerical integration using Monte Carlo methods, estimating π, simulating random walks, and weather forecasting using a Markov Chain model, with accompanying code and discussions on methodology and results. The experiments utilize Python programming and various libraries to visualize data and demonstrate statistical principles.

Uploaded by

Shohanur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Bangabandhu Sheikh Mujibur Rahman Science and

Technology University, Gopalganj-8100

Assignment 2
Course code: CSE:404
Course Name: Computer Simulation and Modeling

Submitted By Submitted To
Name: Md Shohanur Rahman Dr. Syful Islam
ID: 19CSE046 Assistant Professor,
Year:4th Dept. of CSE,BSMRSTU
Semester: 1st
Session: 2019-2020

DATE: 08-09-2024
Experiment Title-1: Sampling Distribution of the Mean from a Uniform Population
Code:
import random
import numpy as np
import matplotlib.pyplot as plt
a=1
b=100
N=10000
DataPop=list(np.random.uniform(a,b,N))
plt.hist(DataPop, density=True, histtype='stepfilled', alpha=0.2)
plt.show()

SamplesMeans = []
for i in range(0,1000):
DataExtracted = random.sample(DataPop,k=100)
DataExtractedMean = np.mean(DataExtracted)
SamplesMeans.append(DataExtractedMean)
plt.figure()
plt.hist(SamplesMeans, density=True, histtype='stepfilled', alpha=0.2)
plt.show()

Input/Output:

Discussion:

This experiment explores the concept of sampling distribution by generating a large uniform population,
drawing random samples from it, and analyzing the distribution of sample means.

Steps Involved:

1. Generating the Population:


o Uniform Population (DataPop):
 10,000 random values are generated from a uniform distribution between a = 1 and b =
100. This represents the entire population of data points.
o Histogram of Population:
 A histogram is plotted to visualize the uniform distribution of the entire population. It shows
how the data is spread across the range from 1 to 100, illustrating the flat, even distribution
of values.
2. Sampling and Calculating Means:
o Sampling:
 1,000 random samples are extracted from the population, with each sample consisting of
100 data points.
 The random.sample() function is used to draw these samples without replacement from
the population.
o Calculating Means:
 For each sample, the mean is calculated using np.mean(), and these means are stored in
the list SamplesMeans.
3. Analyzing the Distribution of Sample Means:
o Histogram of Sample Means:
 A histogram is plotted of the means of the 1,000 samples. This histogram represents
the distribution of sample means, showing how the average value of each sample
varies.

Experiment Title-2: Numerical Integration Using the Monte Carlo Method

Code:
import random
import numpy as np
import matplotlib.pyplot as plt

random.seed(2)
f = lambda x: x**2
a = 0.0

b = 3.0
NumSteps = 1000000
XIntegral=[]
YIntegral=[]
XRectangle=[]
YRectangle=[]

ymin = f(a)
ymax = ymin
for i in range(NumSteps):
x = a + (b - a) * float(i) / NumSteps
y = f(x)
if y < ymin: ymin = y
if y > ymax: ymax = y

A = (b - a) * (ymax - ymin)
N = 1000000
M = 0
for k in range(N):
x = a + (b - a) * random.random()
y = ymin + (ymax - ymin) * random.random()
if y <= f(x):
M += 1
XIntegral.append(x)
YIntegral.append(y)
else:
XRectangle.append(x)
YRectangle.append(y)
NumericalIntegral = M / N * A
print ("Numerical integration = " + str(NumericalIntegral))

XLin=np.linspace(a,b)
YLin=[]
for x in XLin:
YLin.append(f(x))
plt.axis ([0, b, 0, f(b)])
plt.plot (XLin,YLin, color="red" , linewidth="4")
plt.scatter(XIntegral, YIntegral, color="blue", marker =".")
plt.scatter(XRectangle, YRectangle, color="yellow", marker =".")
plt.title ("Numerical Integration using Monte Carlo method")
plt.show()

Input/Output:

Discussion:

This experiment demonstrates numerical integration using the Monte Carlo method to estimate the integral
of a function f(x)=x2 over a given interval [a,b]. The Monte Carlo method uses random sampling to
estimate the area under the curve of a function.

Steps Involved:

1. Setup and Function Definition:


o Function (f): The function to be integrated is f(x) = x^2
o Interval: The integration is performed over the interval [a,b][a, b][a,b], where a=0.0a = 0.0a=0.0 and
b=3.0b = 3.0b=3.0.
2. Calculate Bounding Box:
o Bounding Box Dimensions:
 The minimum (ymin) and maximum (ymax) values of the function f(x)f(x)f(x) over the
interval are calculated. This defines the bounding box used for the Monte Carlo
sampling.
o Area of Bounding Box (A):
 The area of the bounding box is calculated as: A=(b−a)×(ymax−ymin)
3. Monte Carlo Integration:
o Random Sampling:
 N = 1,000,000 random points are sampled within the bounding box.
 For each sample, a random x value and a random y value are generated.
o Count Points Under Curve:
 If the random y value is less than or equal to f(x), the point is considered to be under
the curve.
 Points that fall under the curve are recorded as XIntegral and YIntegral, while
points above the curve are recorded as XRectangle and YRectangle.
o Estimate Integral:
 The integral is estimated by the ratio of points under the curve to the total number of
points, multiplied by the area of the bounding box: NumericalIntegral=(M/N)×A
 Where M is the number of points under the curve.
4. Plotting the Results:
o Plot Function and Points:
 The function f(x) is plotted in red.
 Points under the curve (blue) and points above the curve (yellow) are plotted to visualize
the Monte Carlo sampling process.
o Visualization:
 The plot shows the function f(x),the sampled points, and the areas where the points fall
either under or above the curve.

Experiment Title-3: Monte Carlo Method for Estimating π.


Code:
import math
import random
import numpy as np
import matplotlib.pyplot as plt

N = 10000
M = 0

XCircle=[]
YCircle=[]
XSquare=[]
YSquare=[]

for p in range(N):
x=random.random()
y=random.random()
if(x**2+y**2 <= 1):
M+=1
XCircle.append(x)
YCircle.append(y)
else:
XSquare.append(x)
YSquare.append(y)

Pi = 4*M/N

print("N=%d M=%d Pi=%.2f" %(N,M,Pi))

XLin=np.linspace(0,1)
YLin=[]
for x in XLin:
YLin.append(math.sqrt(1-x**2))

plt.axis ("equal")
plt.grid (which="major")
plt.plot (XLin , YLin, color="red" , linewidth="4")
plt.scatter(XCircle, YCircle, color="yellow", marker =".")
plt.scatter(XSquare, YSquare, color="blue" , marker =".")
plt.title ("Monte Carlo method for Pi estimation")

plt.show()

Input/Output:
Discussion:

This experiment uses the Monte Carlo method to estimate the value of π by simulating random points within
a unit square and determining how many fall inside a quarter circle inscribed within that square.

Steps Involved:

1. Setup:
o Generate Random Points:
 N = 10,000 random points are generated in the unit square [0,1]×[0,1][0, 1] \times
[0, 1][0,1]×[0,1].
2. Check Points Inside Circle:
o Circle Condition:
 Points are checked to see if they fall inside the quarter circle of radius 1, centered at the
origin. The condition is x2+y2≤1.
o Count Points:
 Points inside the circle are counted (M), and their coordinates are stored separately from
points outside the circle.
3. Estimate π\piπ:
o Calculation:
 The estimate of π is calculated using the ratio of points inside the circle to the total number
of points, scaled by 4: π≈4×N/M
4. Visualization:
o Plot:
 The quarter circle is plotted in red.
 Points inside the circle are shown in yellow, while points outside are shown in blue.

Experiment Title-4: 1D Random Walk Simulation.

Code:
from random import seed
from random import random
from matplotlib import pyplot
seed(1)
RWPath = list()
RWPath.append(-1 if random() < 0.5 else 1)
for i in range(1, 1000):
ZNValue = -1 if random() < 0.5 else 1
XNValue = RWPath[i-1] + ZNValue
RWPath.append(XNValue)
pyplot.plot(RWPath)
pyplot.show()

Input/Output:

Discussion:

This experiment simulates a one-dimensional random walk using a simple algorithm where each step is
determined by a random choice between moving forward or backward.

Steps Involved:

1. Initialization:
 Seed Random Generator: Ensures reproducibility by setting the random seed.
 Start Path: Initialize the random walk path with the first step being either -1 or 1, chosen randomly.
2. Simulating the Random Walk:
 Generate Steps:
 For each subsequent step (total of 999 steps):
 Step Direction: A random choice is made to move either -1 or 1.
 Update Position: The new position is computed by adding this step to the
previous position.
 Record Position: The updated position is appended to the path.
3. Plotting the Path:
 Visualization:
 The path of the random walk is plotted, showing how the position changes over time.
Experiment Title-5: Weather Forecasting Using a Markov Chain
Code:
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(3)
StatesData = ["Sunny","Rainy"]

TransitionStates = [["SuSu","SuRa"],["RaRa","RaSu"]]
TransitionMatrix = [[0.80,0.20],[0.25,0.75]]

WeatherForecasting = list()
NumDays = 365
TodayPrediction = StatesData[0]

print("Weather initial condition =",TodayPrediction)

for i in range(1, NumDays):

if TodayPrediction == "Sunny":
TransCondition =
np.random.choice(TransitionStates[0],replace=True,p=TransitionMatrix[0])
if TransCondition == "SuSu":
pass
else:
TodayPrediction = "Rainy"

elif TodayPrediction == "Rainy":


TransCondition =
np.random.choice(TransitionStates[1],replace=True,p=TransitionMatrix[1])
if TransCondition == "RaRa":
pass
else:
TodayPrediction = "Sunny"

WeatherForecasting.append(TodayPrediction)
print(TodayPrediction)

plt.plot(WeatherForecasting)
plt.show()

plt.figure()
plt.hist(WeatherForecasting)
plt.show()

Input/Output:
Discussion:

This experiment simulates weather forecasting using a Markov Chain model. The model predicts weather
states (Sunny or Rainy) for each day based on transition probabilities defined by a transition matrix.

Steps Involved:

1. Setup:
o States and Transition Matrix:
 StatesData: The possible weather states are "Sunny" and "Rainy".
 TransitionStates: Defines possible transitions (e.g., "SuSu" for Sunny to Sunny, "SuRa"
for Sunny to Rainy).
 TransitionMatrix: Probability matrix specifying the likelihood of transitions between states:
 [[0.80, 0.20], [0.25, 0.75]] where:
 0.80 is the probability of remaining Sunny given it was Sunny, and 0.20
is the probability of changing to Rainy.
 0.25 is the probability of changing to Sunny given it was Rainy, and 0.75
is the probability of remaining Rainy.
2. Forecasting Process:
o Initial State: The weather starts as "Sunny".
o Simulation Loop:
 For each day, determine the next state based on the current state and the
transition probabilities.
 Update Prediction:
 Use np.random.choice to randomly select the next state based on the
transition probabilities.
 Update the state for the next iteration.
3. Recording and Plotting Results:
o Weather Forecasting:
 Append the forecasted weather for each day to the WeatherForecasting list.
o Plots:
 Line Plot: Shows the sequence of weather states over the 365 days.
 Histogram: Displays the frequency of each weather state over the year.

You might also like