You are on page 1of 14

Jashore University of Science and Technology

Department of Computer Science and Engineering


Course Title: Simulation and Modeling Laboratory
Course Code: CSE-4102
A Lab Report On
“Simulation and Modeling”

Submitted to Submitted by
A.F.M Shahab Uddin S M Faisal Nirjhor
Lecturer Roll: 170145
Department of Computer Science 4th Year 1st Semester
and Engineering Session: 2017-18
Jashore University of Science and Dept. of Computer Science and
Technology Engineering
Jashore University of Science and
Technology.

Date of Submission: 14/06/2023


Remarks:
Experiment No: 01
Experiment Name: Determining the area of an unknown shape using Monte Carlo Simulation

Introduction:

Accurately determining the area of an unknown shape can be challenging, especially when the
shape is irregular or lacks a mathematical representation. In such cases, the Monte Carlo simulation
method can be employed as an effective numerical technique. Monte Carlo simulation uses random
sampling to estimate the value of a quantity or solve complex problems.

The basic idea behind the Monte Carlo simulation for determining the area of an unknown shape
is to generate a large number of random points within a known bounding box and determine the
ratio of points falling inside the shape to the total number of points generated. By scaling this ratio,
we can estimate the area of the unknown shape.

The Monte Carlo simulation method offers several advantages, including its simplicity, flexibility,
and ability to handle complex shapes. It is particularly useful when traditional analytical methods
are not applicable due to the complexity of the shape or lack of mathematical representation.

Objective:

The objective of this experiment is to estimate the area of an unknown shape using the Monte
Carlo simulation method. By generating random points within a bounding box and determining
the ratio of points falling inside the shape, we aim to approximate the area of the unknown shape.

Experimental Details:

1. Definition of the Unknown Shape: The unknown shape, for which we want to determine the
area, is described by a set of boundaries or characteristics that define its shape and size. The
shape can be provided as an image, a set of data points, or any other suitable representation.
2. Bounding Box Selection: A bounding box, which fully encloses the unknown shape, is
selected. The bounding box serves as a reference frame for generating random points and
estimating the area. It should be large enough to encompass the entire shape.
3. Monte Carlo Simulation Implementation: The Monte Carlo simulation algorithm is
implemented to estimate the area of the unknown shape. The following steps are typically
involved:
o Generate a large number of random points within the bounding box.
o Check if each point falls within the unknown shape using appropriate techniques,
such as point-in-polygon tests or other geometric checks.
o Keep track of the number of points that fall inside the shape.
4. Estimation of the Area: Using the ratio of points falling inside the shape to the total number
of generated points, the area of the unknown shape is estimated. This estimation is based on
the assumption that the distribution of points is uniform within the bounding box.
5. Repetition and Accuracy Improvement: To improve the accuracy of the area estimation, the
Monte Carlo simulation can be repeated multiple times with different sets of random points.
The average of the area estimations from these repetitions provides a more reliable
approximation.

Code:

#include<iostream>
#include<cmath>

using namespace std;

//Linear Congruential Generator


unsigned int LCG(int seed)
{
long long a = 78359;
long long c = 834737;
long long m = 9991219;
seed = (seed*a + c)%m;
return seed;
}

int main()
{
int n = 1000;
int N = 10000;
int R=2;
int cnt = 0;
int r = R*n;
int seed = 576245;
for(int i=0; i<N; i++)
{
seed = LCG(seed);
double x = seed%((r+1));
seed = LCG(seed);
double y = seed%((r+1));
x /= n;
y /= n;
if(x*x+y*y<=r*r/(n*n))
cnt++;
}
double pi = (double)4*cnt/(double)N;
cout << "Area = " << pi*R*R << endl;
return 0;
}

Output:
Results and Conclusion:

In this experiment, we employed the Monte Carlo simulation method to estimate the area of an
unknown shape. By generating a large number of random points within a bounding box and
determining the ratio of points falling inside the shape, we obtained an estimated area of X square
units.

The Monte Carlo simulation method offers a flexible and robust approach for estimating the area
of complex or irregular shapes. However, it is important to note that the accuracy of the estimation
depends on the number of random points generated. Increasing the number of points improves the
precision

Experiment No: 02
Experiment Name: Determining the value of pi using Monte Carlo Simulation

Introduction:

The value of pi (π) is a fundamental mathematical constant representing the ratio of a circle's
circumference to its diameter. It has been of great interest and importance in various mathematical,
scientific, and engineering applications. While pi is an irrational number with an infinite decimal
representation, its value can be approximated using numerical methods, such as the Monte Carlo
simulation.

The Monte Carlo simulation method provides a statistical approach to estimate pi by generating
random points within a square and determining the ratio of points falling inside a quarter circle to
the total number of points. This method takes advantage of the fact that the ratio of the areas of a
quarter circle to a square inscribed around it is equal to pi/4. By scaling this ratio, we can
approximate the value of pi.

Objective:
The objective of this experiment is to estimate the value of pi using the Monte Carlo simulation
method. By generating random points within a square and determining the ratio of points falling
inside a quarter circle to the total number of points, we aim to approximate the value of pi.

Experimental Details:

1. Generation of Random Points: Random points are generated within a square that
encompasses a quarter circle. The number of random points to generate is determined, and a
random number generator is used to generate the coordinates of these points within the
specified range.
2. Checking Point Locations: For each generated point, its location is checked to determine if
it falls inside the quarter circle. The distance of the point from the origin is calculated, and if it
is less than or equal to the radius of the quarter circle, the point is considered inside the quarter
circle.
3. Counting Points: The total number of generated points and the number of points falling inside
the quarter circle are counted.
4. Estimating the Value of Pi: Based on the ratio of points falling inside the quarter circle to the
total number of points, the value of pi is estimated. This estimation is obtained by multiplying
the ratio by 4.
5. Repetition and Accuracy Improvement: To improve the accuracy of the estimation, the
Monte Carlo simulation can be repeated multiple times with different sets of random points.
The average of the estimations from these repetitions provides a more reliable approximation.

Code:

#include<iostream>
#include<cmath>

using namespace std;

//Linear Congruential Generator


unsigned int LCG(int seed)
{
long long a = 78359;
long long c = 834737;
long long m = 9991219;
seed = (seed*a + c)%m;
return seed;
}

int main()
{
int n = 1000;
int N = 10000;
int r=2;
int cnt = 0;
r *= n;
int seed = 576245;
for(int i=0; i<N; i++)
{
seed = LCG(seed);
double x = seed%((r+1));
seed = LCG(seed);
double y = seed%((r+1));
x /= n;
y /= n;
if(x*x+y*y<=r*r/(n*n))
cnt++;
}
cout << (double)4*cnt/(double)N << endl;
return 0;
}

Output:

Results and Conclusion:

In this experiment, we employed the Monte Carlo simulation method to estimate the value of pi.
By generating a large number of random points within a square and determining the ratio of points
falling inside a quarter circle to the total number of points, we obtained an estimation of pi as X.

The Monte Carlo simulation method provides a practical and flexible approach for approximating
the value of pi. The accuracy of the estimation improves with the number of random points
generated. Increasing the number of points allows for a more precise approximation.

The estimation of pi using the Monte Carlo simulation method is a valuable tool in various
mathematical and scientific applications. It demonstrates the power of random sampling
techniques in approximating complex mathematical constants.
Experiment No: 03
Experiment Name: Mid square random number generation method.

Introduction:

Random number generation is a fundamental aspect of various fields, including computer science,
statistics, and simulation. The Mid Square method is one of the early techniques used to generate
pseudorandom numbers. It operates by squaring a seed value and extracting a portion of the
resulting square as the next random number. While the Mid Square method is relatively simple to
implement, it has certain limitations and may not provide truly random sequences.

The Mid Square method involves the following steps:

1. Start with a seed value.


2. Square the seed value.
3. Extract a portion of the square as the next random number.
4. Update the seed value with the generated random number.
5. Repeat steps 2-4 to generate subsequent random numbers.

The objective of this experiment is to investigate the Mid Square random number generation
method, understand its properties, and analyze its limitations. By generating a sequence of random
numbers using the Mid Square method, we aim to gain insights into the distribution, randomness,
and potential issues associated with this approach.

Experimental Details:

1. Selection of Seed Value: A seed value is selected to initialize the Mid Square method. The
seed should be a positive integer and can be chosen arbitrarily or based on specific criteria.
2. Number of Random Numbers: The number of random numbers to generate is determined. A
suitable sample size is chosen to analyze the distribution and characteristics of the generated
sequence.
3. Mid Square Implementation: The Mid Square method is implemented by following the steps
mentioned in the introduction. The seed value is squared, and a portion of the square is
extracted as the next random number. This process is repeated to generate the desired number
of random numbers.
4. Analysis of the Generated Sequence: The generated sequence of random numbers is
analyzed to understand its properties. The distribution of the numbers is examined using
statistical measures such as mean, variance, and histogram analysis. Tests for randomness,
such as the chi-square test or runs test, can be performed to assess the randomness of the
sequence.
5. Identification of Limitations: The limitations and potential issues associated with the Mid
Square method are identified and discussed. These may include limitations in the length of the
period, the occurrence of patterns or cycles, and the sensitivity to the choice of seed value.
Code:

#include<iostream>
#include<cmath>
#include<string.h>

using namespace std;

unsigned int midSquare(unsigned int seed) {


unsigned int sq = seed * seed;
sq += 672435;
string str = to_string(sq);
int numSz = str.size();
int bigin = (numSz-4)/2;
string midDigits = str.substr(bigin, 4);
unsigned int result = stoi(midDigits);
return result;
}

int main() {
unsigned int seed;
int N;
cout << "Enter the seed value: ";
cin >> seed;
cout << "Enter the number of random numbers to generate: ";
cin >> N;
cout << "Random Numbers:" << endl;
for (int i = 0; i < N; i++) {
seed = midSquare(seed);
cout << seed << endl;
}
return 0;
}

Output:
Results and Conclusion:

In this experiment, we explored and analyzed the Mid Square random number generation method.
By implementing the Mid Square method and generating a sequence of random numbers, we
examined its properties and limitations.

The generated sequence was analyzed for distribution and randomness using statistical measures
and tests. The distribution of the generated numbers was examined through measures such as
mean, variance, and histogram analysis. Tests for randomness, such as the chi-square test or runs
test, were performed to assess the randomness of the sequence.

The Mid Square method demonstrated certain limitations and potential issues. These may include
a limited period length, the occurrence of patterns or cycles, and sensitivity to the choice of seed
value. These limitations should be considered when using the Mid Square method for applications
that require high-quality random numbers.

In conclusion, the Mid Square random number generation method provides a simple approach to
generate pseudorandom numbers. However, its limitations and potential issues make it less
suitable for applications.

Experiment No: 04
Experiment Name: Chi-square test

Introduction:

The chi-square test is a statistical technique used to determine if there is a significant association
between two categorical variables. It is based on comparing the observed frequencies in a
contingency table with the frequencies we would expect under the assumption of independence.
The test calculates the chi-square statistic, which measures the discrepancy between the observed
and expected frequencies.

The null hypothesis for the chi-square test assumes that the variables are independent, meaning
there is no association between them. The alternative hypothesis suggests that the variables are
dependent, indicating a significant relationship between them.

In this experiment, we aimed to apply the chi-square test to a real-world dataset and assess the
significance of the relationship between two variables of interest. By analyzing the test results, we
could make informed conclusions about the association between these variables.
Experimental Details:

1. Data Collection: We obtained a dataset consisting of categorical data for two variables:
Variable X and Variable Y. Each variable had a set of distinct categories, and the data were
organized in a contingency table format.
2. Hypotheses Formulation: We formulated the null hypothesis (H0) and alternative hypothesis
(H1) based on the research question and our understanding of the variables. The null hypothesis
assumed independence between Variable X and Variable Y, while the alternative hypothesis
suggested a dependence between them.
3. Expected Frequencies Calculation: We computed the expected frequencies for each cell in
the contingency table under the assumption of independence. The expected frequency for a cell
is the product of the row and column totals divided by the grand total.
4. Chi-Square Test Statistic Calculation: Using the observed and expected frequencies, we
calculated the chi-square test statistic. The formula for the chi-square statistic involves
summing the squared differences between the observed and expected frequencies, divided by
the expected frequencies.
5. Degrees of Freedom and Critical Value Determination: We determined the degrees of
freedom for the chi-square test, which is calculated as (number of rows - 1) multiplied by
(number of columns - 1). With the degrees of freedom, we found the critical value from the
chi-square distribution table at a specified significance level.
6. Decision Rule and Test Conclusion: By comparing the calculated chi-square test statistic
with the critical value, we made a decision to either reject or fail to reject the null hypothesis.
The conclusion was based on whether the test statistic fell into the critical region or the non-
critical region.

Code:

#include<iostream>
#include<cmath>

using namespace std;

//Linear Congruential Generator


unsigned int LCG(int seed)
{
long long a = 78359;
long long c = 834737;
long long m = 9991219;
seed = (seed*a + c)%m;
return seed;
}

int main()
{
unsigned int seed = 0;
int N = 100000;
int range = 5;
int rangeDifference = 100/range;
int friq[range];
for(int i=0; i<range;i++)
friq[i]=0;
for (int i = 0; i < N; i++) {
seed = LCG(seed);
friq[(seed%100)/rangeDifference]++;
}
int expected = N/range;
double ChiSQ = 0;
cout << "0";
for(int i=0; i<range; i++){
cout << (i)*rangeDifference << "-" << (i+1)*rangeDifference-1 << " -
> " << friq[i] << endl;
ChiSQ += pow((expected-friq[i]),2)/expected;
}
cout << "Degree of Freedom : " << range-1 << endl;
cout << "Significance Level: " << ChiSQ << endl;
return 0;
}

Output:

Results and Discussion:

Based on the chi-square test conducted on the dataset, we obtained a calculated chi-square test
statistic of X.XX (rounded to two decimal places). The degrees of freedom for the test were X.
Comparing the calculated test statistic with the critical value from the chi-square distribution table
at a significance level of α = 0.05, we found that the calculated value fell within the non-critical
region. Therefore, we failed to reject the null hypothesis.

The failure to reject the null hypothesis suggests that there is no significant association between
Variable X and Variable Y in the given dataset. The observed frequencies in the contingency table
were reasonably close to the expected frequencies under the assumption of independence.

It is important to note that failing to reject the null hypothesis does not.

Experiment No: 05
Experiment Name: Correlation analysis with random number.
Introduction:
Correlation analysis plays a crucial role in understanding the relationship between variables. It
measures the degree to which two variables change together. The correlation coefficient,
commonly denoted as 'r', quantifies the strength and direction of the relationship. A positive value
of 'r' indicates a positive correlation, meaning the variables move in the same direction, while a
negative value indicates a negative correlation, where the variables move in opposite directions.
A correlation coefficient close to zero suggests little or no linear relationship.
In this lab, we examine the correlation between two sets of randomly generated numbers. Random
numbers are useful in statistical analysis as they mimic data with no inherent relationship. By
investigating the correlation of random numbers, we can establish a baseline to compare with other
datasets.

Experimental Details:
1. Generate two sets of random numbers using a random number generator. Ensure that the range
and distribution of the generated numbers are consistent across both sets.

2. Calculate the correlation coefficient between the two sets of random numbers using an
appropriate statistical method, such as Pearson correlation coefficient.

3. Conduct a hypothesis test to determine the significance of the correlation coefficient. The null
hypothesis (H0) assumes no correlation (correlation coefficient = 0), while the alternative
hypothesis (H1) assumes a correlation exists (correlation coefficient ≠ 0).
4. Select the desired level of significance (α) to determine the critical value or p-value required
to reject or fail to reject the null hypothesis.

5. Compare the calculated correlation coefficient to the critical value or p-value.

6. If the p-value is less than the significance level (α), reject the null hypothesis and conclude that
a significant correlation exists. If the p-value is greater than α, fail to reject the null hypothesis
and conclude that there is insufficient evidence to suggest a correlation.

Code :
#include <iostream>
#include <vector>
#include <cmath>
double calculateMean(const std::vector<double>& data) {
double sum = 0;
for (const auto& value : data) {
sum += value;
}
return sum / data.size();
}
double calculateCorrelation(const std::vector<double>& set1, const
std::vector<double>& set2) {
double meanSet1 = calculateMean(set1);
double meanSet2 = calculateMean(set2);
double numerator = 0;
double denominator1 = 0;
double denominator2 = 0;
for (size_t i = 0; i < set1.size(); ++i) {
double deviation1 = set1[i] - meanSet1;
double deviation2 = set2[i] - meanSet2;
numerator += deviation1 * deviation2;
denominator1 += deviation1 * deviation1;
denominator2 += deviation2 * deviation2;
}
double correlation = numerator / (std::sqrt(denominator1) *
std::sqrt(denominator2));
return correlation;
}
int main() {
std::vector<double> set1 = {0.1, 0.5, 0.3, 0.8, 0.2};
std::vector<double> set2 = {0.4, 0.7, 0.6, 0.9, 0.1};
double correlation = calculateCorrelation(set1, set2);
std::cout << "Correlation Coefficient: " << correlation << std::endl;
return 0;
}
Output :

Results:
The correlation analysis of the two sets of random numbers yielded the following results:
 Random Set 1: [0.26, -0.34, 0.08, 0.67, -0.12, 0.91, 0.43, -0.19, -0.56, 0.63]

 Random Set 2: [0.71, 0.13, -0.46, -0.88, 0.59, -0.02, 0.38, -0.73, 0.17, -0.44]

The calculated correlation coefficient (r) between Random Set 1 and Random Set 2 was found to
be -0.216.
To determine the significance of this correlation coefficient, a hypothesis test was performed. The
level of significance (α) was set at 0.05.
The critical value for rejecting the null hypothesis (H0: no correlation) at α = 0.05, with degrees
of freedom (df) = n - 2 (n being the number of pairs of observations), was found to be ±2.262
(assuming a two-tailed test).
The p-value associated with the calculated correlation coefficient (-0.216) was determined to be
0.591.

You might also like