System Simulation Model Lab Manual
System Simulation Model Lab Manual
Assignment: 03
System Simulation and Modeling
CSX-404
Department of Computer Science and Engineering
Jan-June 2016
Submitted to:
Submitted by:
Contents
Sr. No.
PROGRAM
9.
10.
1.
2.
3.
4.
5.
6.
7.
8.
PAGE No.
SIGNATURE
3
5
7
9
11
13
16
23
33
35
1. Write a program for rolling a fair dice that should generate a discrete random variable,
and draw the graph showing the number of 1's 2's 3's6s.
Theory :
A random number generator (RNG) is a computational or physical device designed to
generate a sequence of numbers or symbols that can not be reasonably predicted better than
by a random chance.
Various applications of randomness have led to the development of several different methods
for generating random data, of which some have existed since ancient times,
including dice, coin flipping, the shuffling of playing cards and many other techniques.
Because of the mechanical nature of these techniques, generating large numbers of
sufficiently random numbers (important in statistics) required a lot of work and/or time.
Thus, results would sometimes be collected and distributed as random number tables.
Nowadays, after the advent of computational random-number generators, a growing number
of government-run lotteries and lottery games have started using RNGs instead of more
traditional drawing-methods. RNGs are also used to determine the odds of modern slot
machines
Code:
#include<bits/stdc++.h>
using namespace std;
int main(){
srand (time(NULL));
int n,i,x;
int Cnt[7];
memset(Cnt,0,sizeof(Cnt));
cout<<"Enter the number of times you want to Roll the dice:\n";
cin>>n;
for(i=0;i<n;i++){
x=rand()%6;
x++;
Cnt[x]++;
}
for(int i=1;i<7;i++)
cout<<"Count of "<<i<<" ="<<Cnt[i]<<endl;
return 0;
}
Output:
Graph:
Output:
Output :
if(((x*x)+(y*y))<=(r*r))
n++;
}
float pi;
pi=4*n/N;
cout<<"The value of PI calculated by Monte Carlo Simulation is "<<pi;
return 0;
}
Output:
10
I=2+(0.1)*Yr;
Yr=45.45+(2.27)*(I+G[i]);
Tx=(0.2)*Yr;
C=20+(0.7)*(Yr-Tx);
cout<<"Value of I: "<<I<<" Value of C: "<<C<<endl<<endl;
}
}
Output:
12
Output:
13
Graphs:
14
service time distribution, and one server. Queuing theory provides exact theoretical
results for some performance measures of an M/M/1 queuing system and this model
makes it easy to compare empirical results with the corresponding theoretical results.
Calling population is infinite. Arrival rate does not change. Units are served according
FIFO
Arrivals are defined by the distribution of the time between arrivals (inter-arrival time)
Service times are according to a distribution
Arrival rate must be less than service rate (stable system)
Otherwise waiting line will grow unbounded (unstable system)
Structure:
The model includes the components listed below:
Time Based Entity Generator block: It models a Poisson arrival process by generating
entities (also known as "customers" in queuing theory).
Exponential Interarrival Time Distribution subsystem: It creates a signal representing
the interarrival times for the generated entities. The interarrival time of a Poisson arrival
process is an exponential random variable. FIFO Queue block: It stores entities that
have yet to be served.
Single Server block: It models a server whose service time has an exponential
distribution.
Code:
import java.util.*;
import java.text.*;
import java.util.*;
class RandTool {
static final long m = 2147483647L;
static final long a = 48271L;
static final long q = 44488L;
static final long r = 3399L;
static long r_seed = 12345678L;
static Random rand = new Random (r_seed);
16
queue.simulate (1000);
System.out.println (queue);
}
}
// Class Customer (one instance per customer) stores whatever we
// need for each customer. Since we collect statistics on waiting
// time at the time of departure, we need to record when a
// customer arrives.
class Customer {
double arrivalTime;
public Customer (double arrivalTime){
this.arrivalTime = arrivalTime;
}
}
// Class Event has everything we need for an event: the type of
// event, and when it occurs. To use Java's PriorityQueue, we need
// have this class implement the Comparable interface where
// one event is "less" if it occurs sooner.
class Event implements Comparable {
public static int ARRIVAL = 1;
public static int DEPARTURE = 2;
int type = -1;
// Arrival or departure.
double eventTime;
// When it occurs.
public Event (double eventTime, int type){
this.eventTime = eventTime;
this.type = type;
}
public int compareTo (Object obj){
Event e = (Event) obj;
if (eventTime < e.eventTime) {
return -1;
}
else if (eventTime > e.eventTime) {
return 1;
}
else {
return 0;
}
}
public boolean equals (Object obj){
return (compareTo(obj) == 0);
}
20
Output:
21
While you might alternatively model the situation as a pair of servers without a queue
between them, the absence of the queue means that if the first server completes service on an
entity before the second server is available, the entity must stay in the first server past the end
of service and the first server cannot accept a new entity for service until the second server
becomes available.
22
Two queue-server pairs connected in parallel, in which each entity arrives at one or the other,
represent alternative operations. For example, vehicles wait in line for one of several
tollbooths at a toll plaza.
23
areas as distinct queue blocks facilitates viewing the average length of time that entities stay in
the overflow storage area.
// statistics:
static double meanArrival = 1;
static double meanService = 0.5;
static int maxNumberOfTasks = 100;
public static int taskCount = 0;
// simulation clock
static double simTime = 0.0;
// random number generators for arrival and departure
static Random rng1 = new Random();
static Random rng2 = new Random();
// future event set
static PriorityQueue<Event> eventSet = new PriorityQueue<Event>();
// servers (with queues)
static Server server1 = new Server();
static Server server2 = new Server();
static Dispatcher dispatcher = new Dispatcher(eventSet, server1, server2);
public static void main (String args[]){
if (args.length == 0) {
System.err.println("Parameters: \n"+
" 1. Mean inter-arrival time \n" +
" 2. Mean service time \n" +
" 3. Number of tasks \n" +
" 4. Seed 1 for arrival times \n" +
" 5. Seed 2 for service times");
System.exit(0);
}
if (args.length > 0) {
try {
meanArrival = Double.parseDouble(args[0]);
} catch (NumberFormatException e) {
System.err.println("First argument must be a floating point value");
System.exit(1);
}
}
if (args.length > 1) {
try {
meanService = Double.parseDouble(args[1]);
25
} catch (NumberFormatException e) {
System.err.println("Second argument must be a floating point
value");
System.exit(1);
}
}
if (args.length > 2) {
try {
maxNumberOfTasks = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.err.println("Third argument must be an integer");
System.exit(1);
}
}
if (args.length > 3) {
try {
long seed = Integer.parseInt(args[3]);
rng1.setSeed(seed);
} catch (NumberFormatException e) {
System.err.println("4th argument must be an integer");
System.exit(1);
}
}
if (args.length > 4) {
try {
long seed = Integer.parseInt(args[4]);
rng2.setSeed(seed);
} catch (NumberFormatException e) {
System.err.println("5th argument must be an integer");
System.exit(1);
}
}
// Generate first event:
eventSet.add( new ArrivalEvent( getNextArrival() ) );
taskCount++;
// Main loop:
while (!eventSet.isEmpty() && taskCount < maxNumberOfTasks){
Event e = eventSet.poll();
dispatcher.handleEvent(e);
}
26
// printing results:
System.out.println("Server 1:");
System.out.println("Utilization " + server1.getUtilization());
System.out.println("Waiting Time " + server1.getAvgWaitingTime());
System.out.println("Queue Length " + server1.getAvgQueueLength());
System.out.println("Server 2:");
System.out.println("Utilization " + server2.getUtilization());
System.out.println("Waiting Time " + server2.getAvgWaitingTime());
System.out.println("Queue Length " + server2.getAvgQueueLength());
/* // brief output:
System.out.println("Server1: " + server1.getUtilization()
+" "+
server1.getAvgWaitingTime()
+" "+
server1.getAvgQueueLength() );
System.out.println("Server2: " + server2.getUtilization()
+" "+ server2.getAvgWaitingTime()
+" "+
server2.getAvgQueueLength() );
*/
}
static public double getNextArrival() {
return simTime + randomExponential(rng1, 1/meanArrival);
}
static public double getNextDeparture() {
return simTime + randomExponential(rng2, 1/meanService);
}
static double randomExponential(Random rng, double lambda) {
return Math.log( rng.nextDouble() ) / -lambda;
}
static public void setSimTime(double t) {
simTime = t;
}
static public double getSimTime() {
return simTime;
}
}
27
}
public String toString() {
return "Departure Event, No. " + number +", scheduled time = " + scheduledTime;
}
}
class Dispatcher {
PriorityQueue<Event> eventSet; // pointer to event set
Server server1, server2;
// pointers to servers
Server currentServer;
public Dispatcher(PriorityQueue<Event> eventSet, Server s1, Server s2) {
server1 = s1;
server2 = s2;
currentServer = s1;
this.eventSet = eventSet;
}
public void handleEvent(Event e) {
Simulation.setSimTime(e.getScheduledTime());
System.out.println("Handling event: " + e);
if (e instanceof ArrivalEvent)
handleArrival( (ArrivalEvent)e );
else
handleDeparture( (DepartureEvent)e );
}
public void handleArrival(ArrivalEvent e) {
// Task assignment rule:
// If both servers are idle, then tasks are assigned alterningly
// Otherwise, the server with the shorter queue is assigned the task
if (server1.getQueueLength() < server2.getQueueLength())
currentServer = server1;
else if (server1.getQueueLength() > server2.getQueueLength())
currentServer = server2;
else if (currentServer == server1) currentServer = server2;
else currentServer = server1;
// Task assignment:
currentServer.assignTask(e.getScheduledTime());
29
Task t = queue.poll();
// calculate statistics:
tasksCompleted++;
busyTimeTotal += Simulation.getSimTime() - t.activationTime;
waitTimeTotal += t.activationTime - t.arrivalTime;
cumulatedQueueLength += (t.activationTime - t.arrivalTime) * (queue.size()+1);
System.out.println("activation: " + t.activationTime + " arrival: " + t.arrivalTime);
// if the queue is not empty, then the next task is activated
if (!queue.isEmpty())
((Task)queue.peek()).activationTime = Simulation.getSimTime();
}
public int getQueueLength() {
return queue.size();
}
public boolean isIdle() {
return queue.isEmpty();
}
public double getUtilization() {
return busyTimeTotal / Simulation.getSimTime();
}
public double getAvgWaitingTime() {
return waitTimeTotal / tasksCompleted;
}
public double getAvgQueueLength() {
return cumulatedQueueLength / Simulation.getSimTime();
}
}
Output:
31
32
if (ESk<=X){
UD = Y;
DDt = i + 3;
Ct = Ct / 80;
}
i = i + 1;
}
printf("\n\n X = %f\n Y=%f\n Z=%f\n\n", X, Y, Ct);
}
Output:
34
35
Class Customer
Customer has methods call(), pickup(), hangup() and merge() for managing calls.
public class Customer {
private String name;
privateintareacode;
private Vector calls = new Vector();
/**
* unregister a call */
protected void removeCall(Call c){
calls.removeElement(c);
}
/**
* register a call */
protected void addCall(Call c){
calls.addElement(c);
}
/**
* Make a new customer with given name */
public Customer(String name, intareacode) {
this.name = name;
this.areacode = areacode;
}
/**
* String rendition of customer */
public String toString() {
return name + "(" + areacode + ")";
}
/**
* what area is the customer in? */
publicintgetAreacode(){
returnareacode;
}
/**
* Is the other customer in the same area? */
publicbooleanlocalTo(Customer other){
returnareacode == other.areacode;
}
/**
* Make a new call to receiver */
36
this.receiver = receiver;
Connection c;
if (receiver.localTo(caller)) {
c = new Local(caller, receiver);
}
else {
c = new LongDistance(caller, receiver);
}
connections.add(c);
}
public void pickup() {
Connection connection = (Connection)connections.lastElement();
connection.complete();
}
publicbooleanisConnected(){
return ((Connection)connections.lastElement()).getState() ==
Connection.COMPLETE;
}
public void hangup(Customer c) {
for(Enumeration e = connections.elements(); e.hasMoreElements();) {
((Connection)e.nextElement()).drop();
}
}
publicboolean includes(Customer c){
boolean result = false;
for(Enumeration e = connections.elements(); e.hasMoreElements();) {
result = result || ((Connection)e.nextElement()).connects(c);
}
return result;
}
public void merge(Call other){
for(Enumeration e = other.connections.elements(); e.hasMoreElements();){
Connection conn = (Connection)e.nextElement();
other.connections.remove(conn);
connections.addElement(conn);
}
}
}
Class Connection
Connection models the physical details of establishing a connection between customers. It does
this with a simple state machine (connections are initially PENDING, then COMPLETED and
finally DROPPED). Messages are printed to the console so that the state of connections can be
observed. Connection is an abstract class with two concrete subclasses: Local and LongDistance.
38
39
super(a, b);
System.out.println("[new local connection from " + a + " to " + b + "]");
}
}
Class LongDistance (in Connection.java) classLongDistance extends Connection {
LongDistance(Customer a, Customer b) {
super(a, b);
System.out.println("[new long distance connection from " + a + " to " + b + "]");
}
}
41