Simulation Practical
Simulation Practical
INDEX
Page
No. Topic Date Sign
No.
Practical-01
1
Single-Channel Queuing Model
Write a C/C++/Excel Program to simulate a Single-Channel Queuing Model.
For C/C++ Programming use the library functions to generate the n-digited random
numbers.
For Excel use the in-built function to generate the n-digited random numbers.
-2-
Given Data:
Distribution of Service Time:
Accept probability values for the Service Time between (1 minute – 6 minutes).
Generate the Random-digit assignment.
Service-Time Distribution:
Service Time Distribution
Service
Cumulative
Time Probability
Probability
(Minutes)
1 0.10 0.10
2 0.20 0.30
3 0.30 0.60
4 0.25 0.85
5 0.10 0.95
6 0.05 1.00
This is service-time distribution in which service time varies from 1 to 6 minutes with the
probabilities.
-3-
Column Description
Customer the customers in order of their arrival.
Inter-arrival Time the inter-arrival time of the customer at the random fashion.
Arrival Time the arrival time of the previous customer and the present customer.
Service Time the estimated time taken by the system to complete the service.
Waiting Time in Queue the time taken by the customers wait in queue.
Time Service Ends the time at which the service to customers ends.
Time Customer spends the total time taken by the customer to complete its service in the system.
Idle Time of Server the time at which server was in idle state.
1.
2.
3.
4.
5.
6.
7.
-4-
Clock Clock Clock
Time
Customer
Waiting Spends
Interarrival Service Time Time Time in Idle Time
Time Arrival Time Service in Queue Service System of Server
Customer (Minutes) Time (Minutes) Begins (Minutes) Ends (Minutes) (Minutes)
1 0 0 4 0 0 4 4 0
2 8 8 4 8 0 12 4 4
3 1 9 2 12 3 14 5 0
4 1 10 2 14 4 16 6 0
5 5 15 2 16 1 18 3 0
6 6 21 3 21 0 24 3 3
7 6 27 6 27 0 33 6 3
8 1 28 4 33 5 37 9 0
9 5 33 2 37 4 39 6 0
10 6 39 5 39 0 44 5 0
11 3 42 4 44 2 48 6 0
12 7 49 3 49 0 52 3 1
13 2 51 1 52 1 53 2 0
14 1 52 4 53 1 57 5 0
15 3 55 4 57 2 61 6 0
16 4 59 2 61 2 63 4 0
17 4 63 4 63 0 67 4 0
18 4 67 1 67 0 68 1 0
19 4 71 3 71 0 74 3 3
20 4 75 3 75 0 78 3 1
75 774 63 799 25 862 88 15
VBA Code:
To insert the Visual Basic Code Tools → Macro → Visual Basic Editor
Module:
Option Explicit
-5-
Function Discrete(Prob As Range, Value As Range)
Dim lRowLast, row As Long
Dim UpperLimit As Double, U As Single
U = Rnd()
lRowLast = Prob.Rows.Count
For row = 1 To lRowLast
UpperLimit = Prob.Cells(row, 1).Value
If U <= UpperLimit Then
Discrete = Value.Cells(row, 1).Value
Exit Function
End If
Next row
Discrete = 0
End Function
Sheet1:
Practical-02
-6-
For C/C++ Programming use the library functions to generate the n-digited random
numbers.
For Excel use the in-built function to generate the n-digited random numbers.
Given:
Inter-arrival Distribution of cars
Accept probability values for the Inter-arrival time between (1 minute - 4 minutes).
Generate the Random-digit assignment.
Service Distribution of Able
Accept probability values for the Service Time between (2 minutes - 5 minutes).
Generate the Random-digit assignment.
Service Distribution of Baker
Accept probability values for the Service Time between (3 minutes - 6 minutes).
Generate the Random-digit assignment.
Total No. of Customers N=20.
Prepare a simulation table and do the subsequent analysis for 20 service completions
and answer the following queries such as find:
1) Percentage of time Able and Baker individually where busy over total
service time.
2) Percentage of arrivals had to wait.
3) The average waiting time for all the customer
4) The average waiting time for the customer who had to wait.
Draw the conclusion regarding the system and cost of waiting.
Given Data:
The time between calls ranges from 1 to 4 minutes with distribution as shown in
following table:
Inter-arrival Time Distribution of Cars:
-7-
Service Distribution of Able:
Accept probability values for the Service Time between (2 minutes - 5 minutes).
Generate the Random-digit assignment.
The problem is to find how well the current arrangement is working, This is the simulation
study for Multi-Channel Queuing System.
Column Description
Arrival Time the arrival time of the previous customer and the present customer
-8-
VBA Code:
-9-
To insert the Visual Basic Code Tools → Macro → Visual Basic Editor
Module:
Option Explicit
Dim lCountCalls As Long
Function Discrete(Prob As Range, Value As Range)
Dim lRowLast, row As Long
Dim UpperLimit As Double, U As Single
U = Rnd()
lRowLast = Prob.Rows.Count
For row = 1 To lRowLast
UpperLimit = Prob.Cells(row, 1).Value
If U <= UpperLimit Then
lCountCalls = lCountCalls + 1
Discrete = Value.Cells(row, 1).Value
Exit Function
End If
Next row
Discrete = 0
End Function
Sheet1:
Private Sub RunTrial_Click()
Sheet1.Calculate
End Sub
Observation:
a) Over the 41-minutes period Able was busy 95.12% of the time.
b) Over the 42-minute period Baker was busy 78.57% of the time. The seniority rule
keeps Baker less busy (and gives Able more tips).
Nine of the 20 arrivals i.e. 45% had to wait.
The average waiting time for all customers was about 1.2 minutes (72 seconds).
The average waiting time for customers who had wait is 3 minutes.
Conclusions:
In summary, this system seems well balanced. One server cannot handle all the diners,
and three servers would probably be too many. Adding an additional server would surely
reduce the waiting time. However, the cost of waiting would have to be quite high to
justify an additional server.
Practical-03
Inventory System
-10-
Write a C/C++/Excel Program to simulate an Inventory System:
(“The Newspaper Seller’s Problem”).
For C/C++ Programming use the library functions to generate the n-digited random
numbers.
For Excel use the in-built function to generate the n-digited random numbers.
Given:
Distribution of Newspapers Demanded
Prepare the simulation table for Purchase of 70 newspapers and find out the total
profit.
Total Profit = (revenue from sales) – (cost of newspapers) –
(lost profit from excess demand) + (salvage from sale of scrap papers)
Theory: An important class of simulation problems involves inventory systems. The total
cost(or total profit) of an inventory system is the measure of performance.
In the following example for deciding how many newspaper to buy, only a single
time period specifies length is relevant, and only a single procurement is made. Inventory
remaining at the end of the single time period is sold for scarp or discarded.
-11-
Demand Probability Distribution
Demand Good Fair Poor
40 0.03 0.10 0.44
50 0.05 0.18 0.22
60 0.15 0.40 0.16
70 0.20 0.20 0.12
80 0.35 0.08 0.06
90 0.15 0.04 0.00
100 0.07 0.00 0.00
The problem is to compute the optimal number of papers the newsstand should purchase.
This will be accomplished simulation demands for 20 days and recording profits from
sales each day.
Following table provide the random digit assignments for the types of newsday’s and the
demands for those newsdays.
Random-Digit Assignment for Type of Newsday:
Type of Newsday
Cumulative
Type Probability
Probability
Good 0.35 0.35
Fair 0.45 0.80
Poor 0.20 1.00
To solve this problem by simulation requires setting a policy of buying a certain number
of papers each day, then simulating the demands for papers over the 20-day time period
-12-
to determine the total profit. The policy(number of newspaper purchased) is changed to
other values and the simulation repeated until the best value is found.
Given Data:
VBA Code:
To insert the Visual Basic Code Tools → Macro → Visual Basic Editor
Module:
Option Explicit
Dim lCountCalls As Long
Function Discrete(Prob As Range, Value As Range)
Dim lRowLast, row As Long
Dim UpperLimit As Double, U As Single
U = Rnd()
lRowLast = Prob.Rows.Count
For row = 1 To lRowLast
UpperLimit = Prob.Cells(row, 1).Value
If U <= UpperLimit Then
lCountCalls = lCountCalls + 1
Discrete = Value.Cells(row, 1).Value
Exit Function
End If
Next row
Discrete = 0
End Function
Sheet1:
Private Sub RunTrial_Click()
Sheet1.Calculate
End Sub
-13-
Lost
Profit
Revenue from Salvage
Type of from Excess from Sale Daily Daily
Day Newsday Demand Sales Demand of Scrap Cost Profit
1 Fair 60 $30.00 $0.00 $0.50 $23.10 $7.40
2 Fair 60 $30.00 $0.00 $0.50 $23.10 $7.40
3 Good 70 $35.00 $0.00 $0.00 $23.10 $11.90
4 Fair 40 $20.00 $0.00 $1.50 $23.10 -$1.60
5 Fair 40 $20.00 $0.00 $1.50 $23.10 -$1.60
6 Fair 60 $30.00 $0.00 $0.50 $23.10 $7.40
7 Fair 80 $35.00 $1.70 $0.00 $23.10 $10.20
8 Fair 80 $35.00 $1.70 $0.00 $23.10 $10.20
9 Poor 40 $20.00 $0.00 $1.50 $23.10 -$1.60
10 Poor 60 $30.00 $0.00 $0.50 $23.10 $7.40
11 Fair 80 $35.00 $1.70 $0.00 $23.10 $10.20
12 Poor 40 $20.00 $0.00 $1.50 $23.10 -$1.60
13 Good 100 $35.00 $5.10 $0.00 $23.10 $6.80
14 Fair 70 $35.00 $0.00 $0.00 $23.10 $11.90
15 Fair 40 $20.00 $0.00 $1.50 $23.10 -$1.60
16 Good 60 $30.00 $0.00 $0.50 $23.10 $7.40
17 Fair 60 $30.00 $0.00 $0.50 $23.10 $7.40
18 Good 70 $35.00 $0.00 $0.00 $23.10 $11.90
19 Fair 70 $35.00 $0.00 $0.00 $23.10 $11.90
20 Fair 50 $25.00 $0.00 $1.00 $23.10 $2.90
TOTAL PROFIT : $124.30
Practical-04
Discrete Distribution
-14-
Theory: Discrete Distributions
Discrete random variables are used to describe random phenomena in which only
integer values can occur. Four distributions are described in the following subsections.
Theory:
The n Bernoulli trials are called a Bernoulli process if the trials are independent, each trial
has only two possible outcome (success (p) & failure (q)), and the probability of success
remains constant from trial to trial. Thus,
p =
Algorithm:
Begin
1) Enter n bernoulli trials.
2) Enter trial no. to check the probability at.
3) Enter the probability of success.
4) Generate random sequence x[i].
5) if x[i]=1
pmf=p
else if x[i]=0
pmf=q
else
pmf=0
6) Mean E(x) = p
7) Variance V(x) = p(1-p)
End
-15-
Theory: The random variable X that denotes the number of success in n Bernoulli Trial has
a binomial distribution given by p where,
Where,
Mean E
Variance V
Algorithm:
Begin
1) Enter the number of trials, n
2) Enter the success in the trials, x
3) Enter the probability in the process, p
4) q=1-p
5) ans=|n|= n!/x!(n-x)!
|x|
6) pmf=p(x)=ans*pow(p,x)pow(q,n-x))
7) mean E(x)= n*p
8) variance V(x) = n*p*q
End
Theory: The geometric distribution is related to a sequence of Bernoulli trials: the random
variable of interest, X, is define to be the number of trials to achieve the first success. The
distribution of X is given by,
-16-
p
Mean E
Variance V
Algorithm:
Begin
1) Enter number of trials.
2) Enter the trials to achieve first success.
3) Enter the probability of success.
4) Evaluate q=1-p.
5) pmf= p(x) = pow(q,x-1)*p for x=1,2,3....n
=0 otherwise
6) Mean E(x)=1/p
7) Variance V(x) =q/p*p
End
Mean E Variance
-17-
The cumulative distribution is given by (cdf)
Algorithm:
Begin
1) Enter total number of trials.
2) Enter the trial no. at which the probability needs to be checked.
3) Enter the mean ( ).
4) if alpha > 0
if x 0 && x n
pmf =p(x)=
else
pmf=0
else
alpha is invalid
5) Cumulative Distribution:
For i=0 to x
F(x) =expo (-alpha)*pow(alpha,i)/i!
6) Mean E(x) = Variance V(x)=alpha
End
-18-
Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
void Bernoulli_Distribution();
void Binomial_Distribution();
void Geometric_Distribution();
void Poisson_Distribution();
long float fact(int);
void main()
{
int choice,flag=1;
clrscr();
while(flag==1)
{
printf("\n\n\t 1:Bernoulli Distribution.");
printf("\n\n\t 2:Binomial Distribution.");
printf("\n\n\t 3:Geometric Distribution.");
printf("\n\n\t 4:Poisson Distribution.");
printf("\n\n\t Enter The Choice Of Distribution : ");
scanf("%d",&choice);
flag=0;
switch(choice)
{
case 1:clrscr();
flag=1;
printf("\t\t\t\tBERNOULLI DISTRIBUTION\n\n");
Bernoulli_Distribution();
break;
case 2:clrscr();
flag=1;
printf("\t\t\t\tBINOMIAL DISTRIBUTION\n\n");
Binomial_Distribution();
break;
case 3:clrscr();
flag=1;
printf("\t\t\t\tGEOMETRIC DISTRIBUTION\n\n");
Geometric_Distribution();
break;
case 4:clrscr();
flag=1;
printf("\t\t\t\tPOISSON DISTRIBUTION\n\n");
Poisson_Distribution();
break;
-19-
Default:
printf("\n You have entered wrong chioce.");
flag=0;
exit(0);
}
}
}
void Bernoulli_Distribution()
{
float p,q,x[100],pmf,a;
int i,n,j;
printf("\n Enter The Total number of Trials(n) : ");
scanf("%d",&n);
printf("\n Enter the probability of success in the experiment (p) : ");
scanf("%f",&p);
q=1-p;
printf("\n\n The Probability of failure is (q) : %f",q);
randomize();
printf("\n\n %d Trials are : \n\n",n);
for(i=0;i<n;++i)
{
a=random(10);
if(x[a]==1)
x[i]=a;
else
x[i]=a*0.01;
printf("%f\t",x[i]);
}
printf("\n\n Enter the Trial number,which you want to check the pmf : ");
scanf("%d",&j);
if(x[j]==1)
pmf=p;
else if(x[j]==0)
pmf=q;
else
pmf=0;
printf("\n\n RESULT :");
printf("\n\n The PMF is : %f",pmf);
printf("\n\n The mean of the Trial is [E(x)] : %f",p);
printf("\n\n The Variance of the Trial is [V(x)] : %f",(p*q));
}
void Binomial_Distribution()
{
float p,q;
-20-
int i,n,x;
long float ans,pmf=0;
printf("\n\nEnter The Number of Trial in Experiments (n) : ");
scanf("%d",&n);
printf("\n\n Enter The number to check the Probability for (x) : ");
scanf("%d",&x);
printf("\n\n Enter The Probability of success in the experiment (p) : ");
scanf("%f",&p);
q=1-p;
printf("\n\nThe Probability of failure in the experiment is (q) : %f",q);
for(i=0;i<=x;++i)
{
if(i==0)
ans=1;
else
ans=(long float)(fact(n)/(fact(i)*fact(n-i)));
//printf("\n ans : %lf",ans);
pmf=pmf+(long float)((ans)*(pow(p,i))*(pow(q,(n-i))));
}
printf("\n\n RESULT :");
printf("\n\n The PMF is : %lf",pmf);
printf("\n\n The mean of the Trial is [E(x)] : %f",n*p);
printf("\n\n The Variance of the Trial is [V(x)] : %f",(n*p*q));
}
void Geometric_Distribution()
{
float p,q,pmf;
int i,n,x;
printf("\n\n Enter The Number of trial to get first success in Experiments : ");
scanf("%d",&x);
printf("\n\n Enter The Probability of Success in The experiments(p) : ");
scanf("%f",&p);
q=1-p;
printf("\n\n The Probability of failure is : %f",q);
if(x>=1)
pmf=(float)(pow(q,x-1)*p);
else
pmf=0;
printf("\n\n RESULT :");
printf("\n\n The PMF is : %f",pmf);
printf("\n\n The mean of the Trial is [E(x)] : %f",(1/p));
printf("\n\n The Variance of the Trial is [V(x)] : %f",(q/(p*p)));
}
void Poisson_Distribution()
-21-
{
long float pmf,cdf=0,factx,expo,alphapow,facti,alphai;
float alpha;
int i,x;
printf("\n\n Enter The Trial you want to check for (x) : ");
scanf("%d",&x);
printf("\n\n Enter The mean for the trial (alpha) : ");
scanf("%f",&alpha);
if(x>=0 && alpha>0)
{
factx=fact(x);
expo=exp(-(alpha));
alphapow=pow(alpha,x);
pmf=(((expo)*(alphapow))/factx);
printf("\n\nPMF is %.3lf",pmf);
for(i=0;i<=x;++i)
{
facti=fact(i);
alphai=pow(alpha,i);
cdf=cdf+(((expo)*(alphai))/facti);
}
printf("\n\n CDF is : %lf",cdf);
}
else
pmf=0;
printf("\n\n The mean and variance of Poisson Distribution is : %f",alpha);
}
long float fact(int n)
{
int i;
long float f=1;
for(i=1;i<=n;++i)
{
f=f*i;
}
return(f);
}
-22-
Output:
/*
!-----------------------------------------------------------------------------------------!
DISCREET DISTRIBUTION
1:Bernoulli Distribution.
2:Binomial Distribution.
3:Geometric Distribution.
4:Poisson Distribution.
BERNOULLI DISTRIBUTION
20 Trials are :
RESULT :
1:Bernoulli Distribution.
2:Binomial Distribution.
3:Geometric Distribution.
-23-
4:Poisson Distribution.
BINOMIAL DISTRIBUTION
RESULT :
1:Bernoulli Distribution.
2:Binomial Distribution.
3:Geometric Distribution.
4:Poisson Distribution.
GEOMETRIC DISTRIBUTION
RESULT :
-24-
The mean of the Trial is [E(x)] : 1.666667
1:Bernoulli Distribution.
2:Binomial Distribution.
3:Geometric Distribution.
4:Poisson Distribution.
GEOMETRIC DISTRIBUTION
RESULT :
1:Bernoulli Distribution.
2:Binomial Distribution.
3:Geometric Distribution.
4:Poisson Distribution.
*/
Practical-05
-25-
Continuous Distributions
Theory: A random variable X is uniformly distributed on the interval (a,b) if its pdf is
given by ,and cdf is given by
-26-
5.2 Exponential Distribution
Theory: A random variable X is said to exponentially distributed with parameter >0 &
its pdf & cdf is given by
-27-
5.3 Erlang Distribution
Theory: The pdf given below is often referred to as Erlang distribution of order k when
= k, an integer. The mean & variance of gamma variance, are valid regardless of value
of . The expected value of the sum of the random, variable is the sum of the expected
value of each random variable. Thus,
The expected value of the exponentially distributed X are each given by 1/k. Thus,
If the random variable X are independent, the variance of their sum is the sum of the
variance, or
-28-
Write a C/C++/Excel Program to find Probability Distribution Function (pdf) and
Cumulative Distribution Function (cdf) for Normal Distribution Accept mean , variance 2
and the transformation variable z = t - / .
Algorithm:
Begin
1) Read the randon variable x,mean,variance.
2) if variance > 0
sigma=sqrt(variance)
pdf=(1/(sigma*sqrt(2*3.142)))*exp((-1/2)*(pow((x-
mean)/sigma,2)));
Note : Its not possible to evaluate cdf in close form
End
-29-
Write a C/C++/Excel Program to find Probability Distribution Function (pdf) and cumulative
Distribution Function (cdf) for Weibull Distribution Accept for a random variable X with the
location parameter , scale parameter > 0, and the shape parameter > 0 from the user.
Theory: The random variable X has a weibull distribution if its pdf has the form
When v = 0 and = 1. Letting = 1 the Weibull Distribution are given by the following
expression.
The mean & variance of the Weibull are given by the following expression :
Where
Algorithm:
Begin
1) Read the random variable x.
2) Read the location parameter v.
3) Read the scale parameter alpha
4) Read the shape parameter beta.
5) if alpha >0 && beta >0
if x > v || v==0
-30-
pdf=(beta/alpha)*(pow((x-v)/alpha,beta-1)*exp(pow(-((x-v)/alpha),beta)));
else
if v == 0 && alpha == 1 && x >= 0
pdf=(1/alpha)*exp(-(x/alpha));
else
pdf=0
if x >= v
cdf=1-exp(-(pow((x-v)/alpha,beta)));
else
cdf=0
End
The mode occurs at x = b. The parameters ( a, b, c) can be related. The cdf is given by
The mean
Where > 0. The mean and variance of lognormal random variable are
-31-
The parameters come from the fact that when Y has N ( ) distribution, then
Y
X = e has a lognormal distribution with parametes . If the mean & variance of
the lognormal are know to be , respectively, then the parameters are
given by
Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
void uniform_distribution();
void exponential_distribution();
void weibull_distribution();
void erlang_distribution();
void normal_distribution();
void triangular_distribution();
void lognormal_distribution();
long fact(int);
void main()
{
int choice,flag=1;
clrscr();
while(flag==1)
{
printf("\n\t\t\t Continuous Distribution.");
printf("\n\n1. Uniform Distribution.");
printf("\n2. Exponential Distribution.");
printf("\n3. Erlang Distribution.");
printf("\n4. Normal Distribution.");
printf("\n5. Weibull Distribution.");
printf("\n6. Triangular Distribution.");
printf("\n7. Lognormal Distribution.");
printf("\n\n\nSelect Any One Of The Options : ");
scanf("%d",&choice);
flag=0;
}
switch(choice)
-32-
{
case 1:
clrscr();
uniform_distribution();
break;
case 2:
clrscr();
exponential_distribution();
break;
case 3:
clrscr();
erlang_distribution();
break;
case 4:
clrscr();
normal_distribution();
break;
case 5:
clrscr();
weibull_distribution();
break;
case 6:
clrscr();
triangular_distribution();
break;
case 7:
clrscr();
lognormal_distribution();
break;
default:
break;
}
getch();
}
void uniform_distribution()
{
float a,b,x,pdf,cdf,mean,variance;
float f[10];
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Uniform Distribution ");
printf("\nEnter a = ");
scanf("%f",&a);
printf("\nEnter b = ");
scanf("%f",&b);
printf("\nEnter Random Variable(x) = ");
scanf("%f",&x);
if(a<=x && x<=b)
{
pdf=1/(b-a);
printf("\nPDF is %.3f.",pdf);
-33-
}
else
{
pdf=0;
printf("\nPDF is %.3f.",pdf);
}
if(x<a)
{
printf("\nCDF is 0.");
}
else if(a<=x && x<b)
{
cdf=(x-a)/(b-a);
printf("\nCDF is %.3f.",cdf);
}
else if(x>=b)
{
printf("\nCDF is 1.");
}
mean=(a+b)/2;
variance=pow((b-a),2)/12;
printf("\n\nMean E(x) = %.3f.",mean);
printf("\nVariance V(x) = %.3f.",variance);
getch();
}
void exponential_distribution()
{
float lambda,x,pdf,cdf,mean,variance;
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Exponential Distribution");
printf("\n\nEnter random variable(x) = ");
scanf("%f",&x);
printf("\nEnter parameter(lambda) = ");
scanf("%f",&lambda);
if(lambda < 0)
{
printf("\nError : lamda should be greater than 0");
exit(0);
}
else
{
if(x>=0)
{
pdf=lambda*(exp(-lambda*x));
printf("\nPDF is %.3f",pdf);
cdf=1-(exp(-lambda*x));
printf("\nCDF is %.3f",cdf);
}
else
{
-34-
x=0;
printf("\n PDF is 0");
printf("\n CDF is 0");
}
}
mean=1/lambda;
variance=1/pow(lambda,2);
printf("\n\nMean E(x) = %f",mean);
printf("\nVariance V(x) = %f",variance);
getch();
}
void erlang_distribution() //has only cdf no pdf
{
float theta,k,cdf,sum,x,mean,variance;
int i,flag=0;
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Erlang Distribution");
printf("\n\nEnter the Shape parameter(Beta)= ");
scanf("%f",&k);
while(flag==0)
{
if( k <= 0)
{
printf("\nError : Beta should be greater than zero.");
flag=0;
}
else
flag=1;
}
printf("\nEnter the scale parameter(theta)= ");
scanf("%f",&theta);
printf("\nEnter the random variable(x) = ");
scanf("%f",&x);
if(x>0)
{
for(i=0;i<k;i++)
{
sum=sum+(((exp(-k*theta*x))*pow(k*theta*x,i))/fact(i));
cdf=1-sum;
}
printf("\nCDF = %.4f",cdf);
}
else
printf("\nCDF = 0");
mean=pow(theta,-1);
variance=1/(k*pow(theta,2));
printf("\n\nMean = %.3f",mean);
printf("\nVariance = %.3f",variance);
getch();
}
void normal_distribution()
-35-
{
float variance,sigma,mean,x,pdf;
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Normal Distribution\n");
printf("\nEnter random variable(x)= ");
scanf("%f",&x);
printf("\nEnter the mean= ");
scanf("%f",&mean);
printf("\nEnter The variance(sigma^2)= ");
scanf("%f",&variance);
if(variance<0)
{
printf("\n\nError : Variance should be greater than zero.");
exit(0);
}
sigma=sqrt(variance);
pdf=(1/(sigma*sqrt(2*3.142)))*exp((-1/2)*(pow((x-mean)/sigma,2)));
printf("\nPDF is %.3f",pdf);
printf("\nMean is %.3f",mean);
printf("\nVariance is %.3f",variance);
getch();
}
void weibull_distribution()
{
float x=0,alpha=0,beta=0,v=0,mean=0,variance=0,ans=0;
float pdf=0,cdf=0,ans1=0;
int flag=0;
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Weibull Distribution\n");
printf("\n\nEnter the random variable(x)= ");
scanf("%f",&x);
while(flag==0)
{
printf("\nEnter the value for shape paramater(beta)= ");
scanf("%f",&beta);
printf("\nEnter the value for scale parameter(alpha)= ");
scanf("%f",&alpha);
if(alpha>0 && beta>0)
flag=1;
else
{
printf("\nError : Value of alpha and beta should be greater than
zero");
flag=0;
}
}
printf("\nEnter value for location parameter(v)= ");
scanf("%f",&v);
if(x>=v || v==0)
-36-
{
ans1=(x-v)/alpha;
pdf=(beta/alpha)*pow(ans1,beta-1)*exp(pow(-ans1,beta));
printf("\n\nResults : ");
printf("\nPDF is %.3f",pdf);
}
else
if(v==0 && alpha==1 && x>=0)
{
pdf=(1/alpha)*exp(-(x/alpha));
printf("\n\nResults :");
printf("\nPDF is %.3f",pdf);
}
else
printf("\nPDF is 0.");
if(x>=v)
{
cdf=1-exp(-(pow( ((x-v)/alpha),beta)));
printf("\nCDF is %.3f",cdf);
}
else
{
printf("\nCDF is 0");
}
mean=(float)v+( alpha * fact(1/beta));
ans=fact(2/beta)-pow(fact(1/beta),2);
variance=(float)pow(alpha,2)*ans;
printf("\n\nMean E(X) = %.0f",mean);
printf("\n\nThe variance V(X) = %.0f",variance);
getch();
}
void triangular_distribution()
{
float a,b,c,x,cdf,pdf,r1,mean,var,mode;
int flag=1;
printf("\t\t\t CONTINIOUS DISTRIBUTION");
printf("\n\n\t\t\t Triangular Distribution");
printf("\n\nEnter the random variable x :");
scanf("%f",&x);
printf("\nEnter the parameter values such that a<=b<=c :");
while(flag==1)
{
printf("\nEnter a = ");
scanf("%f",&a);
printf("\nEnter b = ");
scanf("%f",&b);
printf("\nEnter c = ");
scanf("%f",&c);
if(a<=b && b<=c)
flag=0;
-37-
else
{
printf("\nError : The values should be as a<=b<=c\n");
flag=1;
}
}
if(a<=x && x<=b)
{
pdf=(2*(x-a))/((b-a)*(c-a));
}
else
{
if(b<x && x<=c)
{
pdf=(2*(c-x))/((c-b)*(c-a));
}
else
pdf=0;
}
if(x <= a)
cdf=0;
-38-
scanf("%f",&mul);
printf("\n\nEnter the value for (Sigma)L^2 = ");
scanf("%f",&sl);
mu=log((mul*mul)/(sqrt((mul*mul)+(sl))));
sigma=log(((mul*mul)+(sl))/(mul*mul));
ans1=1/(sqrt(2*3.142) * sqrt(sigma) * x);
ans2=exp(-(pow(log(x)-mu,2)/(2*pow(sigma,2))));
if(x>0)
{
pdf=ans1*ans2;
}
else
{
pdf=0;
}
mean=exp(mu+((sigma*sigma)/2));
variance=exp((2*mu)+(sigma)) * (exp(sigma)-1);
printf("\n\nResults :");
printf("\nPDF is %.3f",pdf);
printf("\nCDF is %.3f",cdf);
printf("\nThe meu is %.3f",mu);
printf("\nThe sigma is %.3f",sigma);
printf("\nThe mean is %.3f",mean);
printf("\nThe variance is %.3f",variance);
}
long fact(int num)
{
long f=1;
int i;
for(i=num;i>=1;i--)
f=f*i;
return(f);
}
Output :
/*
CONTINIOUS DISTRIBUTION
Uniform Distribution
Enter a = 1
Enter b = 2
PDF is 1.000.
-39-
CDF is 0.300.
Exponential Distribution
Enter x = 2
PDF is 0.171
CDF is 0.486
Erlang Distribution
CDF = 0.4536
Mean = 60.241
Variance = 1209.658
Normal Distribution
PDF is 0.133
Mean is 50.000
Variance is 9.000
Weibull Distribution
-40-
Enter value for location parameter v = 0
Results :
PDF is 0.000
CDF is 0.884
Triangular Distribution
Enter b = 1.1
Enter c = 6.5
Results :
PDF is 0.230
CDF is 0.541
Mean is 2.550
The mode is 1.100
Lognormal Distribution
Results :
PDF is 0.000
CDF is 0.000
The meu is 2.965
The sigma is 0.061
The mean is 19.439
The variance is 25.000
!---------------------------------------------------------------------------------------!
*/
-41-
Practical-06
Theory:
Random Number Generation
Random numbers are necessary basic ingredient in the simulation of almost all discrete
system. Most computer languages have a subroutine or function that will generate a
random number.
6.1 Linear Congruential Method : The liner congruential method produces a sequence of
random integers between zero & m – 1 according to the following recursive
relationships
The initial vale Xo is called the seed, a is called the constant multiplier, c is the increment,
and m is the modulus. If c not equal to zero, the form is called the mixed congruential
method. When c is equal to zero, the form is called as multiplicative congruential method.
Algorthim:
-42-
Begin
1. Read the constant multiplier a, incremental factor c, value of modulus m,
seed x0, Number of random numbers to be generated.
2. for i=0 to n
x[i+1]=(a*x[i]+c)mod m
r[i+1]=(x[i+1]/m)
Note : I f c=0 then it is known as multiplicative congruential method
if c!=0 then it is known as mived congruential method.
End
Is uniformly distributed on the integer 0 to m -2. The jth generator is producing integer X
that are approximately uniformly distributed on 1 to m -1, and is
approximately uniformly distributed on 0 to m -2. Thus the suggested combined generator of
the form
with
R =
-43-
Code :
#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<stdlib.h>
void linear_congruential();
void combined_linear_congruential();
void main()
{
int flag=1,choice;
clrscr();
while(flag==1)
{
printf("\n\n\t\t\t Random Number Generation");
printf("\n\n1. Linear Congruential Method.");
printf("\n2. Combined Linear Congruential Method.");
printf("\n\nEnter your choice =");
scanf("%d",&choice);
flag=0;
}
switch(choice)
{
case 1:
clrscr();
linear_congruential();
break;
case 2:
clrscr();
combined_linear_congruential();
break;
default:
exit(0);
}
getch();
}
void linear_congruential()
{
int a,c,m,x[50],n,i;
float r[50];
printf("\n\n\t\t\t Random Number Generation");
-44-
printf("\n\n\t\t\t Linear Congruential Method");
printf("\n\n\nEnter the value for constant multiplier a : ");
scanf("%d",&a);
printf("\nEnter the value for increment c : ");
scanf("%d",&c);
printf("\nEnter the value for modulus m : ");
scanf("%d",&m);
printf("\nEnter the value for seed x0 : ");
scanf("%d",&x[0]);
printf("\n\nHow many random numbers do you want to be generated : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
x[i+1]=(a*x[i]+c)%m;
r[i+1]=(float)x[i+1]/m;
}
printf("\n\nRandom Integers\t\tRandom Numbers\n\n");
for(i=1;i<=n;i++)
{
printf("%d",x[i]);
printf("\t\t\t%0.3f",r[i]);
printf("\n");
}
getch();
}
void combined_linear_congruential()
{
long x[20],x1[20][20],m[5],sum,rg,n,a[5],i,j,temp;
double r[20];
printf("\n\n\t\t\t Random Number Generation");
printf("\n\n\t\t Combined Linear Congruential Method");
printf("\n\n\nEnter number of random no. generators you want = ");
scanf("%ld",&rg);
printf("\n\nEnter how many random numbers you want to generate = ");
scanf("%ld",&n);
for (i=0;i<rg;i++)
{
printf("\n\nGenerator %d :",i+1);
printf("\n\nEnter the value of constant multiplier a : ");
scanf("%ld",&a[i]);
printf("\nEnter the value of modulus m : ");
scanf("%ld",&m[i]);
printf("\nEnter the Seed value x0 : ");
scanf("%ld",&x1[i][0]);
}
printf("\n\nRandom numbers are : \n\n\n");
printf("Random Integer");
printf("\tRandom Number\n\n\n");
for (j=0;j<rg;j++)
-45-
{
for (i=0;i<n;i++)
{
x1[j][i+1]=(a[j]*x1[j][i])%m[j];
}
}
for (i=0;i<n;i++)
{
sum=0;
for (j=0;j<rg;j++)
{
temp=pow((-1),j);
sum=sum+((temp)*(x1[j][i]));
}
x[i]=sum%(m[0]-1);
if (x[i]>0)
{
r[i]=(double)x[i]/m[0];
}
else if(x[i]==0)
{
r[i]=(double)(m[0]-1)/m[0];
}
printf("%.3ld",x[i]);
printf("\t%.3lf",r[i]);
printf("\n");
}
getch();
}
/*
Output
Random Number Generation
-46-
9 0.090
65 0.650
61 0.610
97 0.970
73 0.730
!-----------------------------------------------------------------------------------------!
Generator 1 :
Generator 2 :
Generator 3 :
003 0.125
004 0.167
004 0.167
018 0.750
-47-
004 0.167
017 0.708
*/
Practical-07
Gap Test: Accept N random numbers level of significance , Find the number of
gaps for all digits occurring in the random number sequence
Algorithm:
-48-
Step1 : Rank the data from smallest to largest. Let R(i) denote the ith smallest
observation, so that
Step2 : Compute
Step4: Determine the critical value, Dα , from Table A.8 for the specified significance
the level α and the given sample size N
Step5: If the sample statistic D is greater than the critical value Dα, the null
hypothesis that the data are a sample from the uniform distribution is rejected.
If D D α, conclude that no difference has been detected between the true
distribution of { } and the uniform distribution
Accept n random numbers and level of significance to reject or accept the given set of
random numbers
-49-
Runs up and Runs Down Test: Accept the total number of runs a to find the mean and
variance of a
The runs test examines the arrangement of numbers in a sequence to test the
hypothesis of independence. A run is defined as a succession of similar events preceded
followed by a different run. The length of the run is the number of events that occur in the
run..
If a is the total number of runs in a truly random sequence, the mean ans the variance
of a are given by
A ‘+’ sign will be used to denote an observation above mean, and a ‘_’
sign will denote an observation below the mean.
Runs below and above mean test: Accept the number of individual observations above and
below the mean as N1 and N2, the total number of runs as b to find the mean and variance
for b
The test for runs up and down is not completely adequate to assess the independence of a
group of numbers. Let n1 and n2 be the individual observation above and below the mean
and Let b be the total numbers of runs. The maximum number of runs is N = n1 + n2 and the
minimum number of run is one. Given n1 & n2 the mean and variance are give by,
and,
-50-
For either n1 or n2 greater than 20, b is approximately normally distributed. The test statistic
can be formed by subtracting the mean from the number of runs & diving by the standard
deviation, or
The tests for autocorrelation are concerned with the dependence between numbers in
a sequence . The test requires the computation of autocorrelation bwtween every m numbers
( m is also known as the lag ) starting with the i th number. Thus, the autocorrelation
between the following numbers would be of the interest:
. The value M is the largest integer such that i +
(M+1) m , where N is the total number of values in a sequence. The formula for is
given by
and
-51-
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
int flag=1,choice;
clrscr();
while(flag==1)
{
printf("\t\t\t\tRANDOM NUMBER TEST\n");
printf("\n\n1) Kolmogorov-Simrnov Test");
printf("\n\n\n\t\t\t\tRUN TEST");
printf("\n\n2) Runs up and runs down. ");
printf("\n3) Runs above the mean & below the mean");
printf("\n4) Test for Autocorrelation");
printf("\n\nEnter your choice : ");
scanf("%d",&choice);
flag=0;
}
switch(choice)
{
case 1:
clrscr();
ks_test();
break;
case 2:
clrscr();
runUp_runDown();
break;
case 3:
clrscr();
runAboveMean_runBelowMean();
break;
case 4:
clrscr();
auto_correlation();
-52-
break;
default:
exit(0);
}
getch();
}
void ks_test()
{
float r[100],temp=0,a[100],b[100],c[100],temp1=0,max_b,max_c,max_d,alpha,d_critical;
int i=0,j=0,N=0;//flag1=1;
char b1,c1;
printf("\t\t\t\t FREQUENCY TEST");
printf("\n\n\t\t\t Kolmogorov-Simrnov Test ");
printf("\n\nEnter the number of random numbers to be generated : ");
scanf("%d",&N);
printf("\n\nNote : Sinificance level alpha should be from : 0.10 0.05 0.01");
while(flag1==1)
{
printf("\nEnter the significance level alpha : ");
scanf("%f",&alpha);
if(alpha!=(float)0.10 || alpha!=(float)0.05 || alpha!=(float)0.01)
{
printf("\nError :Incorrect Value of alpha");
alpha=0;
flag1=1;
}
else
flag1=0;
}
printf("\n\nEnter the critical value of D for alpha=%f at N=%d : ",alpha,N);
scanf("%f",&d_critical);
randomize();
for(i=1;i<=N;i++)
{
r[i]=random(100)*(0.01);
if( r[i] == 0.00 )
r[i]=random(10)*(0.1);
}
//Step 1 : rank the random numbers in ascending order
for(i=1;i<=N;i++)
{
for(j=i+1;j<=N;j++)
{
if( r[i] > r[j] )
{
temp=r[i];
r[i]=r[j];
r[j]=temp;
}
-53-
}
}
printf("\n\nR[i]\t\t i/N\t\t (i/N-R[i]) R[i]-(i-1)/N");
for(i=1;i<=N;i++)
{
a[i]=(float)i/N;
b[i]=a[i]-r[i];
temp1=(float)(i-1)/N;
c[i]=r[i]-temp1;
if(b[i] < 0)
{
b1=' ';
printf("\n%.2f\t\t %.2f\t\t %c\t \t%.2f",r[i],a[i],b1,c[i]);
}
else if(c[i] < 0)
{
c1=' ';
printf("\n%.2f\t\t%.2f\t\t %.f\t %c ",r[i],a[i],b[i],c1);
}
else
printf("\n%.2f\t\t%.2f\t\t %.2f\t %.3f ",r[i],a[i],b[i],c[i]);
}
//To find the max
max_b=b[1];
max_c=c[1];
for(i=1;i<N;i++)
{
max_b=(float)max(b[i+1],max_b);
max_c=(float)max(c[i+1],max_c);
}
printf("\n\n\nD+ = max{ (i/N)-R(i) } for 1 <= i <= N");
printf("\n\nMax { i/N-R(i) (D+) } =%.3f",max_b);
printf("\n\n\nD- = max { (R(i)-(i-1)/N) } for 1 <= i <= N");
printf("\n\nMax { R(i)-(i-1)/N } =%.3f",max_c);
max_d=max(max_b,max_c);
printf("\n\n\nD = Max(D+,D-) = %.3f",max_d);
printf("\n\nResult :");
if(max_d < d_critical)
{
printf("\n\nSince the computed value of D=%.3f is less than given
D=%.3f",max_d,d_critical);
printf("\nthe hypothesis of no difference between the distribution of
generated number");
printf("\n& the uniform distribution is not rejected");
}
else
{
printf("\n\nSince the computed value of D=%f is greater than given
D=%f ,",d_critical);
printf("\nthe hypothesis of no difference between the distribution of
generated number");
-54-
printf("\n& the uniform distribution is rejected");
}
getch();
}
void runUp_runDown()
{
float r[100],meu_a=0,sigma_a=0,a=0,Z=0,alpha=0.025,a_critical=1.96;
char runs[100];
int N=0,i=0,flag=1,ctr1=0,ctr2=0;
printf("\t\t\t\t RUN TEST");
printf("\n\n\t\t\t Runs up runs Down Test ");
printf("\n\nEnter the number of random numbers to be generated : ");
scanf("%d",&N);
printf("\n\n");
//printf("\n\nEnter the significane level (alpha)= ");
//scanf("%f",&alpha);
randomize();
printf("\n\n\nRandom Numbers : \n");
for(i=1;i<=N;i++)
{
r[i]=random(100)*(0.01);
if( r[i] == 0.00 )
r[i]=random(10)*(0.1);
printf("%.2f ",r[i]);
}
meu_a=(float)(2*N-1)/3;
sigma_a=(float)(16*N-29)/90;
for(i=1;i<N;i++)
{
if(r[i] < r[i+1])
{
runs[i]='+';
}
else
{
runs[i]='-';
}
}
printf("\n\n\n ");
//Calculates the number of length of runs.
for(i=0;i<N-1;i++)
{
if(runs[i]==runs[i+1])
{
while(runs[i]==runs[i+1])
{
i=i+1;
}
ctr1=ctr1+1;
//again i is incremented from the for loops
}
-55-
else
ctr2=ctr2+1;
}
a=ctr1+ctr2;
Z=(float)((a-meu_a)/sqrt(sigma_a));
printf("\n\nRuns: \n\n");
for(i=1;i<N;i++)
{
printf("%c ",runs[i]);
}
printf("\n\n\nMean (mue) = %.3f ",meu_a);
printf("\n\nVariance (sigma) = %.3f ",sigma_a);
printf("\n\nObserved number of runs (a)= %.3f",a);
printf("\n\nZ= %.3f",Z);
printf("\n\n\n\nResult :");
if( Z < a_critical)
{
printf("\n\nSince, the critical value of Z = %.3f less that
Z(%.3f)=%.3f" ,Z,alpha,a_critical);
printf(" the independence cannot be rejected");
}
else
{
printf("\n\nSince, the critical value of Z = %.3f not less than
Z(%.3f)=%.3f," ,Z,alpha,a_critical);
printf("\nthe independence is rejected");
}
getch();
}
void runAboveMean_runBelowMean()
{
float r[100],meu_b=0,sigma_b=0,b=0,Z=0,alpha=0.025;
float a_critical=1.96,p1=0,p2=0,p3=0;
char runs[100];
int N=0,i=0,n1=0,n2=0,ctr1=0,ctr2=0;
printf("\t\t\t\t RUN TEST");
printf("\n\n\t\t\t Runs Above & below the mean");
printf("\n\nEnter the number of random numbers to be generated : ");
scanf("%d",&N);
printf("\n\n");
//printf("\n\nEnter the significane level (alpha)= ");
//scanf("%f",&alpha);
randomize();
printf("\n\n\nRandom Numbers : \n");
for(i=1;i<=N;i++)
{
r[i]=random(100)*(0.01);
if( r[i] == 0.00 )
r[i]=random(10)*(0.1);
printf("%.2f ",r[i]);
-56-
}
for(i=1;i<N;i++)
{
if(r[i] > 0.495)
{
runs[i]='+';
}
else
{
runs[i]='-';
}
}
printf("\n\nRuns :\n\n");
for(i=1;i<N;i++)
{
printf("%c ",runs[i]);
}
for(i=1;i<N;i++)
{
if(runs[i] == '+')
n1++;
else
n2++;
}
printf("\n\nn1=%d",n1);
printf("\n\nn2=%d",n2);
meu_b=(float)(2*n1*n2/N)+0.5;
p1=2*n1*n2;
p2=p1*(p1-N);
p3=pow(N,3)-N;
sigma_b=(float)(p2/p3);
for(i=0;i<N-1;i++)
{
if(runs[i]==runs[i+1])
{
while(runs[i]==runs[i+1])
{
i=i+1;
}
ctr1=ctr1+1;
//again i is incremented from the for loops
}
else
ctr2=ctr2+1;
}
b=ctr1+ctr2;
if(n1 > 20 || n2 > 20)
{
Z=(float)(b-meu_b)/sqrt(sigma_b);
}
printf("\n\n\nMean (mue) = %.3f ",meu_b);
-57-
printf("\n\nVariance (sigma) = %.3f ",sigma_b);
printf("\n\nObserved number of runs (b)= %.3f",b);
printf("\n\nZ= %.3f",Z);
printf("\n\n\nResult : ");
if( Z < a_critical)
{
printf("\n\nSince, the critical value of Z = %.3f less that Z(%.3f)=%.3f,\
n",Z,alpha,a_critical);
printf("the independence cannot be rejected");
}
else
{
printf("\n\nSince, the critical value of Z = %.3f not less than Z(%.3f)=%.3f\
n",Z,alpha,a_critical);
printf("\nthe independence is rejected");
}
getch();
}
void auto_correlation()
{
float r[100],meu_a=0,sigma_a=0,alpha=0.025,a_critical=1.96,ans=0,rho=0,sigma=0,Z=0;
int N=0,j=0,flag=1,i=0,M=0,m=0;
printf("\t\t\t\t TEST OF AUTO CORRELATION");
printf("\n\n\nEnter the number of random numbers to be generated : ");
scanf("%d",&N);
printf("\n\n");
//printf("\n\nEnter the significane level (alpha)= ");
//scanf("%f",&alpha);
randomize();
//Accept & prints Random Numbers
printf("\n\nRandom Numbers : \n\n");
for(j=1;j<=N;j++)
{
r[j]=random(100)*(0.01);
if( r[j] == 0.00 )
r[j]=random(10)*(0.1);
printf("%.2f ",r[j]);
}
printf("\n\nEnter the lag m (every m numbers)= ");
scanf("%d",&m);
printf("\n\nEnter the gap to test i (starting from i'th number) = ");
scanf("%d",&i);
printf("\n\nNote : Enter the Value of M such that i+(M-1)*m <= N \n\n");
while(flag==1)
{
printf("Enter M (largest integer)= ");
scanf("%d",&M);
if(i+(M+1)*m >= N)
{
printf("\n\nIncorrect Value of M\n\n");
flag=1;
-58-
}
else
{
flag=0;
}
}
for(j=0;j<=M;j++)
{
ans=ans+r[i+j*m]*r[i+(j+1)*m];
}
rho=(pow((M+1),-1))*ans-0.25;
float s1=0,s2=0;
s1=(float)sqrt((13*M)+7);
s2=(float)12*(M+1);
sigma=(float)s1/s2;
Z=rho/sigma;
printf("\n\nrho(%d)(%d) = %.3f",i,m,rho);
printf("\n\nsigma = %.3f",sigma);
printf("\n\nZ(%.3f)(%d) = %.3f ",alpha,N,Z);
printf("\n\n\nResult : \n\n");
if( Z < a_critical)
{
printf("\n\Since, the critical value of Z = %.3f less that
Z(%.3f)=%.3f,\n",Z,alpha,a_critical);
printf("the independence cannot be rejected");
}
else
{
printf("\n\nSince, the critical value of Z = %.3f not less than
Z(%.3f)=%.3f\n",Z,alpha,a_critical);
printf("\nthe independence is rejected");
}
getch();
}
-59-
Output:
/*
!-----------------------------------------------------------------------------------------!
FREQUENCY TEST
Kolmogorov-Simrnov Test
D = Max(D+,D-)= 0.410
Result :
Since the computed value of D=0.410 is less than given D=0.565 the hypothesis of no difference
between the distribution of generated number
& the uniform distribution is not rejected
!-----------------------------------------------------------------------------------------!
-60-
!-----------------------------------------------------------------------------------------!
RUN TEST
Random Numbers :
0.53 0.34 0.19 0.28 0.21 0.50 0.53 0.52
0.58 0.55 0.20 0.87 0.55 0.48 0.58 0.43
0.60 0.71 0.13 0.21 0.92 0.60 0.64 0.09
0.91 0.01 0.91 0.93 0.15 0.28 0.39 0.49
0.15 0.44 0.26 0.13 0.97 0.97 0.25 0.00
0.05 0.96 0.77 0.46 0.47 0.86 0.40 0.68
0.28 0.66
Runs:
--+-++-+--+--+-++-++-+-+-++-+++-+--+---+
+--++-+-+
Z= 0.342
Result :
Since, the critical value of Z = 0.342 less that Z(0.025)=1.960 the independence
cannot be rejected
!-----------------------------------------------------------------------------------------!
RUN TEST
Random Numbers :
0.84 0.15 0.79 0.52 0.56 0.48 0.80 0.63
0.21 0.78 0.62 0.78 0.83 0.57 0.70 0.27
0.19 0.57 0.37 0.50 0.75 0.43 0.17 0.11
-61-
0.15 0.73 0.33 0.67 0.71 0.74 0.04 0.69
0.69 0.39 0.68 0.60 0.71 0.92 0.55 0.47
0.18 0.67 0.17 0.24 0.01 0.52 0.74 0.50
0.39 0.02
Runs :
+-+++-++-++++++--+-++----+-+++-++-+++++-
-+---+++-
n1=30
n2=19
Z= 0.476
Result :
Since, the critical value of Z = 0.476 less that Z(0.025)=1.960, the independence cannot be rejected
!-----------------------------------------------------------------------------------------!
Random Numbers :
-62-
rho(3)(3) = 0.015
sigma = 0.128
Z(0.025)(30) = 0.121
Result :
Since, the critical value of Z = 0.121 less that Z(0.025)=1.960, the independence cannot be rejected
!-----------------------------------------------------------------------------------------!
*/
Practical-08
-63-
Acceptance-Rejection Technique
Write a C/C++/Excel Program to implement Acceptance-Rejection Technique for a
given Distribution( Poisson or Gamma distribution).
Theory:
Acceptance . Rejection technique
Suppose that an analyst needed to devise a method for generating random
variables X uniformly distributed between ¼ & 1.
The steps used area-
Step 1- Generate a random no. R
Step 3- Of another uniform random variable on [1/4, 1] is needed repeat the procedure
beginning at step 1, or not stop.
8.1 Poisson Distribution: A Poisson random variable, N, with mean α > 0 has pmf
N can be interpreted as the number of arrivals from the Poisson arrival process in one unit of
time.
Algorithim:
Step1 : n=0, P=1
Step2 : Generate a random number R and replace P by P. R
-α
Step3 : if p < e , then accept N = n. Otherwise, reject the surrent n, increase n
by one, and retuen to step 2.
Step3 : Compute X =
-64-
Code :
//Acceptance-rejection Technique
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
void poisson_distribution();
void gamma_distribution();
void main()
{
int choice;
clrscr();
x:
printf("\n\n Acceptance-Rejection Techinque");
printf("\n 1: Poisson Distribution");
printf("\n 2: Gamma Distribution");
printf("\n 3: Exit");
switch(choice)
{
case 1:
clrscr();
poisson_distribution();
goto x;
case 2:
clrscr();
gamma_distribution();
goto x;
case 3:
exit(0);
}
getch();
void poisson_distribution()
{
float n=0,P=1,R[20],alpha,q;
int x,count=0,N=0;
-65-
printf("\n\n Enter the number of Poisson variates : ");
scanf("%d",&x);
randomize();
//Replace P by P*R[n+1]
P=P*R[n+1];
if(P<q)
{
N=n;
count++;
P=1;
}
else
{
//print the values in table with "Reject"
printf("\n %d",n);
printf("\t %.3f",R[n+1]);
printf("\t\t %.3f",P);
printf("\t Reject");
printf("\t\t\t %d",N);
n++;
}
}
getch();
-66-
void gamma_distribution()
{
float a,b,beta,R1,R2,V,X,Y,theta,Z;
int flag=1;
a=1/pow(((2*beta)-1),0.5);
b=(beta)-(log(4));
while(flag==1)
{
R1=rand()%100/(float)100;
R2=rand()%100/(float)100;
V=R1/(1-R1);
X=beta*(pow(V,a));
Z=((R1*R1)*R2);
Y=b+ ( (beta*a)+1) * ( log(V) ) - ( log (Z) ) ;
printf("\n\n R1=%f",R1);
printf("\n\n R2=%f",R2);
printf("\n\n V=%f",V);
printf("\n\n X=%f",X);
printf("\n\n Y=%f",Y);
if (X>Y)
{
printf("\n\n X=%f has been rejected as %f>%f",X,X,Y);
flag=1;
}
else
{
printf("\n\n X=%f has been accepted as %f<=%f",X,X,Y);
X=X/(beta*theta);
printf("\n\n The accepted value of X after using the formula
[X/(beta*theta)] is %f ",X);
flag=0;
}
}
getch();
-67-
OUTPUT :
Poisson Distribution
Acceptance-Rejection Techinque
1: Poisson Distribution
2: Gamma Distribution
3: Exit
Enter Choice : 2
Gamma Distribution
R1=0.460000
R2=0.300000
V=0.851852
X=2.928360
Y=4.131284
-68-