Вы находитесь на странице: 1из 14

Reasons for simulating system

1) Economy
2) Unavailability of real system.
With simulation a decision maker can try out new design, layouts, software programs
and systems before committing resources to their acquiring or implementation.

System Modeling

Model is defined as the body of information about a system gathered for the
purpose of studying the system. Since the purpose of the study will determine the nature of the
information that is gathered, there is no unique model of a system.

Types of Models
MODELS

PHYSICAL MATHEMATICAL

STATIC DYNAMIC
STATIC DYNAMIC

NUMERICAL ANALYTICAL NUMERICAL

SYSTEM SIMULATION

Models will first be separated into physical models or mathematical models.


Physical models are based on some analogy between such systems as mechanical and
electrical, or electrical and hydraulic,. In a physical model of a system, the system attributes are
represented by such measurements as voltage or the position of a shaft.

Mathematical models use symbolic notation and mathematical equations to represent a


system. The system attributes are represented by variables, and the activities are represented by
mathematical functions that interrelate the variables.

A second distinction will be between static models and dynamic models.

Static Physical Models

Static model can only show the values that system attributes take when the system
is in balance. The best known examples of physical models are scale models. In shipbuilding,
making a scale model provides a simple way of determining the exact measurements of the
plates covering the hull, rather than having to produce drawings of complicated, three-
dimensional shapes. Scale models are also used in wind tunnels and water tanks in the course of
designing aircraft and ships. Although air is blown over the model, or the model is pulled
through the water, these are static physical models because the measurements that are taken
represent attributes of the system being studied under one set of equilibrium conditions.
Sometimes, a static physical model is used as a means of solving equations with particular
boundary conditions.

Dynamic Physical Models


Dynamic models follow the changes over time that result from the system
activities. Dynamic physical models rely upon an analogy between the system being studied and
some other system of a different nature, the analogy usually depending upon an underlying
similarity in forces governing the behavior of the systems.

Static Mathematical Models


Static models depict conditions of state. If the equilibrium condition changes, new
values may be obtained analytically, but the model does not indicate the manner in which the
system achieved its new state. A numerical solution is required in order to optimize the
system parameters.

A static model gives the relationships between the system attributes when the system is
in equilibrium. If the point of equilibrium is changed by altering any of the attribute values, the
model enables the new values for all attributes to be derived but does not show the way in which
they changed to their new values.

For example, in marketing a commodity there is a balance between the supply and
demand for the commodity. Both factors depend upon price: a simple market model will show
what the price at which the balance occurs is. Demand for the commodity will be low when the
price is high, and it will increase as the price drops.

Dynamic Mathematical Models


Dynamic models depict conditions that vary with time. Simple dynamic models
can be solved analytically, and the results represented graphically. Complex dynamic models
can be solved using numerical methods.

A Dynamic Mathematical Model allows the changes of system attributes to be derived


as function of time. The derivation may be made with an analytical solution or with a numerical
computation, depending upon the complexity of the model.

When to simulate

Simulation provides alternative gap filling between exact analysis and physical requirements and it is
also cheap and fast. Used in science and engineering research when developing physical models like
aircraft simulator, network analyzers, river basin models and lab experiments. Used in very important
fields like biology, medicine, economics, mathematical areas where large problems involving thousands
of variables are solved. Used by business executives in problem solving when advance concepts like
operational research, dynamics programming and research tools fail. Used for training without cost of
the experiment.

When simulation cannot be done?


If the problems can be solved analytically direct experiments performed must not be simulated,
simulation must not be performed if there are no proper resources or time if costs exceeds saving.

How to simulate
Suppose we are interested in a gas station. We may describe the behavior of this system graphically by
plotting the number of cars in the station; the state of the system. Every time a car arrives the graph
increases by one unit while a departing car causes the graph to drop one unit. This graph (called sample
path), could be obtained from observation of a real station, but could also be artificially constructed.
Such artificial construction and the analysis of the resulting sample path (or more sample paths in more
complex cases) constitute the process of simulation.

INTRODUCTION TO DISCRETE SYSTEM:

In discrete-event simulation, the operation of a system is represented as a chronological sequence


of events. Each event occurs at an instant in time and marks a change of state in the system. For
example, if an elevator is simulated, an event could be "level 6 button pressed", with the resulting
system state of "lift moving" and eventually (unless one chooses to simulate the failure of the lift) "lift at
level 6".

A common exercise in learning how to build discrete-event simulations is to model a queue, such as
customers arriving at a bank to be served by a teller. In this example, the system entities are
CUSTOMER-QUEUE and TELLERS. The system events are CUSTOMER-ARRIVAL and
CUSTOMER-DEPARTURE. (The event of TELLER-BEGINS-SERVICE can be part of the logic of the
arrival and departure events.) The system states, which are changed by these events, are NUMBER-OF-
CUSTOMERS-IN-THE-QUEUE (an integer from 0 to n) and TELLER-STATUS (busy or idle). The
random variables that need to be characterized to model this system stochastically are CUSTOMER-
INTERARRIVAL-TIME and TELLER-SERVICE-TIME.

A number of mechanisms have been proposed for carrying out discrete-event simulation, among
them are the event-based, activity-based, process-based and three-phase approaches (Pidd, 1998). The
three-phase approach is used by a number of commercial simulation software packages, but from the
user's point of view, the specifics of the underlying simulation method are generally hidden.

• Components of a Discrete-Event Simulation


In addition to the representation of system state variables and the logic of what happens when
system events occur, discrete event simulations include the following:

Clock
The simulation must keep track of the current simulation time, in whatever measurement units
are suitable for the system being modeled. In discrete-event simulations, as opposed to real time
simulations, time ‘hops’ because events are instantaneous – the clock skips to the next event start
time as the simulation proceeds.
Events List
The simulation maintains at least one list of simulation events. This is sometimes called the
pending event set because it lists events that are pending as a result of previously simulated event
but have yet to be simulated themselves. An event is described by the time at which it occurs and
a type, indicating the code that will be used to simulate that event. It is common for the event
code to be parameterised, in which case, the event description also contains parameters to the
event code.
When events are instantaneous, activities that extend over time are modeled as sequences of
events. Some simulation frameworks allow the time of an event to be specified as an interval,
giving the start time and the end time of each event.
Single-threaded simulation engines based on instantaneous events have just one current event. In
contrast, multi-threaded simulation engines and simulation engines supporting an interval-based
event model may have multiple current events. In both cases, there are significant problems with
synchronization between current events.
The pending event set is typically organized as a priority queue, sorted by event time.[2] That is,
regardless of the order in which events are added to the event set, they are removed in strictly
chronological order. Several general-purpose priority queue algorithms have proven effective for
discrete-event simulation,[3] most notably, the splay tree. More recent alternatives include skip
lists and calendar queues.[4]
Typically, events are scheduled dynamically as the simulation proceeds. For example, in the
bank example noted above, the event CUSTOMER-ARRIVAL at time t would, if the
CUSTOMER_QUEUE was empty and TELLER was idle, include the creation of the subsequent
event CUSTOMER-DEPARTURE to occur at time t+s, where s is a number generated from the
SERVICE-TIME distribution.

Random-Number Generators
The simulation needs to generate random variables of various kinds, depending on the system
model. This is accomplished by one or more Pseudorandom number generators. The use of
pseudorandom numbers as opposed to true random numbers is a benefit should a simulation need
a rerun with exactly the same behaviour.
One of the problems with the random number distributions used in discrete-event simulation is
that the steady-state distributions of event times may not be known in advance. As a result, the
initial set of events placed into the pending event set will not have arrival times representative of
the steady-state distribution. This problem is typically solved by bootstrapping the simulation
model. Only a limited effort is made to assign realistic times to the initial set of pending events.
These events, however, schedule

Random-Number Generators
The simulation needs to generate random variables of various kinds, depending on the system
model. This is accomplished by one or more Pseudorandom number generators. The use of
pseudorandom numbers as opposed to true random numbers is a benefit should a simulation need
a rerun with exactly the same behaviour.
One of the problems with the random number distributions used in discrete-event simulation is
that the steady-state distributions of event times may not be known in advance. As a result, the
initial set of events placed into the pending event set will not have arrival times representative of
the steady-state distribution. This problem is typically solved by bootstrapping the simulation
model. Only a limited effort is made to assign realistic times to the initial set of pending events.
These events, however, schedule additional events, and with time, the distribution of event times
approaches its steady state. This is called bootstrapping the simulation model. In gathering
statistics from the running model, it is important to either disregard events that occur before the
steady state is reached or to run the simulation for long enough that the bootstrapping behavior is
overwhelmed by steady-state behavior. (This use of the term bootstrapping can be contrasted
with its use in both statistics and computing.)

Statistics
The simulation typically keeps track of the system's statistics, which quantify the aspects of
interest. In the bank example, it is of interest to track the mean waiting times.

Ending Condition
Because events are bootstrapped, theoretically a discrete-event simulation could run forever. So
the simulation designer must decide when the simulation will end. Typical choices are “at time t”
or “after processing n number of events” or, more generally, “when statistical measure X reaches
the value x”.

Simulation Engine Logic


The main loop of a discrete-event simulation is something like this:

Start
• Initialize Ending Condition to FALSE.
• Initialize system state variables.
• Initialize Clock (usually starts at simulation time zero).
• Schedule an initial event (i.e., put some initial event into the Events List).

“Do loop” or “While loop”


While (Ending Condition is FALSE) then do the following:
• Set clock to next event time.
• Do next event and remove from the Events List.
• Update statistics.

End
• Generate statistical report.
INTRODUCTION TO C++

Three important aspects of any language are the way it stores data, how it accomplishes
input and output and the operators it uses to transform and combine data.

The language that satisfied out needs of being reliable, simple and easy to use is ‘C’. It is
friendly, capable and strong.

C is one language that stands in between the two levels of programming languages.

1. High Level Languages or problem oriented languages: These


languages have been designed to give a better programming efficiency, i.e., faster program
development.

Ex. FORTRAN, BASIC, PASCAL, etc.

2. Machine oriented language or Low Level Languages: These


languages have been designed to give a better machine efficiency, i.e., faster program execution.

Ex. Assembly language and machine language.

○ C stands in between these two categories. That is why it is often called a Middle
Level Language, since it was designed to have both: a relatively good
programming efficiency (as compared to Machine Oriented Languages) and
relatively good machine efficiency (as compared to problem oriented languages).

○ C is a one man language, i.e., it was developed by Dennis Ritchie at “AT and T’s
bell Laboratories” of USA in the year 1972. It became popular immediately and
has maintained this status even today thus making it our first choice.

C is often used for "system programming", including implementing operating systems and
embedded system applications, due to a combination of desirable characteristics such as code
portability and efficiency, ability to access specific hardware addresses, ability to pun types to
match externally imposed data access requirements, and low runtime demand on system
resources. C can also be used for website programming using CGI as a "gateway" for
information between the Web application, the server, and the browser.[11] Some reasons for
choosing C over interpreted languages are its speed, stability, and near-universal availability.[12]

• One consequence of C's wide acceptance and efficiency is that compilers, libraries, and
interpreters of other programming languages are often implemented in C. The primary
implementations of Python (CPython), Perl 5, and PHP are all written in C.

• Due to its thin layer of abstraction and low overhead, C allows efficient implementations
of algorithms and data structures, which is useful for programs that perform a lot of
computations. For example, the GNU Multi-Precision Library, the GNU Scientific
Library, Mathematica and MATLAB are completely or partially written in C.

• C is sometimes used as an intermediate language by implementations of other languages.


This approach may be used for portability or convenience; by using C as an intermediate
language, it is not necessary to develop machine-specific code generators. Some
languages and compilers which have used C this way are BitC, C++, Eiffel, Gambit,
GHC, Squeak, and Vala. However, C was designed as a programming language, not as a
compiler target language, and is thus less than ideal for use as an intermediate language.
This has led to development of C-based intermediate languages such as C--.

• C has also been widely used to implement end-user applications, but much of that
development has shifted to newer languages

• C has a static weak typing type system that shares some similarities with that of other
ALGOL descendants such as Pascal. There are built-in types for integers of various sizes,
both signed and unsigned, floating-point numbers, characters, and enumerated types
(enum). C99 added a boolean datatype. There are also derived types including arrays,
pointers, records (struct), and untagged unions (union).

• C is often used in low-level systems programming where escapes from the type system
may be necessary. The compiler attempts to ensure type correctness of most expressions,
but the programmer can override the checks in various ways, either by using a type cast
to explicitly convert a value from one type to another, or by using pointers or unions to
reinterpret the underlying bits of a value in some other way.
• Pointers
• C supports the use of pointers, a very simple type of reference that records, in effect, the
address or location of an object or function in memory. Pointers can be dereferenced to
access data stored at the address pointed to, or to invoke a pointed-to function. Pointers
can be manipulated using assignment and also pointer arithmetic. The run-time
representation of a pointer value is typically a raw memory address (perhaps augmented
by an offset-within-word field), but since a pointer's type includes the type of the thing
pointed to, expressions including pointers can be type-checked at compile time. Pointer
arithmetic is automatically scaled by the size of the pointed-to data type. (See Array-
pointer interchangeability below.) Pointers are used for many different purposes in C.
Text strings are commonly manipulated using pointers into arrays of characters. Dynamic
memory allocation, which is described below, is performed using pointers. Many data
types, such as trees, are commonly implemented as dynamically allocated struct objects
linked together using pointers. Pointers to functions are useful for callbacks from event
handlers.

• A null pointer is a pointer that points to no valid location by having a value of 0.[17]
Dereferencing a null pointer is therefore meaningless, typically resulting in a run-time
error. Null pointers are useful for indicating special cases such as no next pointer in the
final node of a linked list, or as an error indication from functions returning pointers. In
code, null pointers are usually represented by 0 or NULL.

• Void pointers (void *) point to objects of unknown type, and can therefore be used as
"generic" data pointers. Since the size and type of the pointed-to object is not known,
void pointers cannot be dereferenced, nor is pointer arithmetic on them allowed, although
they can easily be (and in many contexts implicitly are) converted to and from any other
object pointer type.

• Careless use of pointers is potentially dangerous. Because they are typically unchecked, a
pointer variable can be made to point to any arbitrary location, which can cause
undesirable effects. Although properly-used pointers point to safe places, they can be
made to point to unsafe places by using invalid pointer arithmetic; the objects they point
to may be deallocated and reused (dangling pointers); they may be used without having
been initialized (wild pointers); or they may be directly assigned an unsafe value using a
cast, union, or through another corrupt pointer. In general, C is permissive in allowing
manipulation of and conversion between pointer types, although compilers typically
provide options for various levels of checking. Some other programming languages
address these problems by using more restrictive reference types.

• Arrays
• Array types in C are traditionally of a fixed, static size specified at compile time. (The
more recent C99 standard also allows a form of variable-length arrays.) However, it is
also possible to allocate a block of memory (of arbitrary size) at run-time, using the
standard library's malloc function, and treat it as an array. C's unification of arrays and
pointers (see below) means that true arrays and these dynamically-allocated, simulated
arrays are virtually interchangeable. Since arrays are always accessed (in effect) via
pointers, array accesses are typically not checked against the underlying array size,
although the compiler may provide bounds checking as an option. Array bounds
violations are therefore possible and rather common in carelessly written code, and can
lead to various repercussions, including illegal memory accesses, corruption of data,
buffer overruns, and run-time exceptions.

• Although C supports static arrays, it is not required that array indices be validated
(bounds checking). For example, one can try to write to the sixth element of an array with
five elements, generally yielding undesirable results. This type of bug, called a buffer
overflow or buffer overrun, is notorious for causing a number of security problems. Since
bounds checking elimination technology was largely nonexistent when C was defined,
bounds checking came with a severe performance penalty, particularly in numerical
computation. A few years earlier, some Fortran compilers had a switch to toggle bounds
checking on or off; however, this would have been much less useful for C, where array
arguments are passed as simple pointers.

• C does not have a special provision for declaring multidimensional arrays, but rather
relies on recursion within the type system to declare arrays of arrays, which effectively
accomplishes the same thing. The index values of the resulting "multidimensional array"
can be thought of as increasing in row-major order.

• Multidimensional arrays are commonly used in numerical algorithms (mainly from


applied linear algebra) to store matrices. The structure of the C array is well suited to this
particular task. However, since arrays are passed merely as pointers, the bounds of the
array must be known fixed values or else explicitly passed to any subroutine that requires
them, and dynamically sized arrays of arrays cannot be accessed using double indexing.
(A workaround for this is to allocate the array with an additional "row vector" of pointers
to the columns.)

• C99 introduced "variable-length arrays" which address some, but not all, of the issues
with ordinary C arrays.

• See also: C string

• Array-pointer interchangeability
• A distinctive (but potentially confusing) feature of C is its treatment of arrays and
pointers. The array-subscript notation x[i] can also be used when x is a pointer; the
interpretation (using pointer arithmetic) is to access the (i + 1)th object of several
adjacent data objects pointed to by x, counting the object that x points to (which is x[0])
as the first element of the array.

• Formally, x[i] is equivalent to *(x + i). Since the type of the pointer involved is
known to the compiler at compile time, the address that x + i points to is not the address
pointed to by x incremented by i bytes, but rather incremented by i multiplied by the
size of an element that x points to. The size of these elements can be determined with the
operator sizeof by applying it to any dereferenced element of x, as in n = sizeof *x or
n = sizeof x[0].

• Furthermore, in most expression contexts (a notable exception is as operand of sizeof),


the name of an array is automatically converted to a pointer to the array's first element;
this implies that an array is never copied as a whole when named as an argument to a
function, but rather only the address of its first element is passed. Therefore, although
function calls in C use pass-by-value semantics, arrays are in effect passed by reference.

• The number of elements in a declared array x can be determined as sizeof x / sizeof


x[0].

• An interesting demonstration of the interchangeability of pointers and arrays is shown


below. The four assignments are equivalent and each is valid C code.
C header files are used to provide a way of telling the compiler what interface specific functions
require in order to be used. The compiler has no interest in what the source code actually does,
but it does need to know how to interface to that code, and the header file gives it that
information.

Every external function will be mentioned in a header file, including libraries that are pre-
compiled into object code, and source files required to build the C program. We will look at the
standard header files, user defined header files, and how they fit into the compiling and linking
sequence.

Standard Header Files

By now, the reader should be aware that there are many operations that are not catered for in the
C programming language; string manipulation, for example. However, the creators of all
compiler sets will make available a set of libraries to provide this 'missing' functionality.

These are collectively known as the standard libraries and include:

• string.h : for string handling

• stdlib.h : for some miscellaneous functions

• stdio.h : standardized input and output

• math.h : mathematical functions

We place references to these at the start of the source code file that uses one or more functions
from that library. So, a simple hello world application might require the formatted output offered
in the stdio.h header file:

#include // Formatted I/O


void main ( void ) // Entry point function
{
printf("Hello World"); // Output
}

This program simply writes Hello World to the screen. What is important to note is that the code
for the function printf is not defined in the program itself, but in a library that comes pre-
compiled. The compiler can compile the source code above, thanks to the #include line, which
tells it where the definition of printf can be found

Вам также может понравиться