Assignment2
Assignment2
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:
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:
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
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.
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]
if TodayPrediction == "Sunny":
TransCondition =
np.random.choice(TransitionStates[0],replace=True,p=TransitionMatrix[0])
if TransCondition == "SuSu":
pass
else:
TodayPrediction = "Rainy"
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.