mobile comm-simulatiion 22

198
M. Sc. Part I [COMPUTER SCIENCE] Practical Journal [Mobile Computing] Seat Number [ ] Department of Computer Science and Information Technology Deccan Education Society’s Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

Upload: api-26413529

Post on 11-Apr-2015

150 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Mobile Comm-Simulatiion 22

M. Sc. Part I [COMPUTER SCIENCE] Practical Journal [Mobile Computing]

Seat Number [ ]

Department of Computer Science and Information Technology Deccan Education Society’s

Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

Page 2: Mobile Comm-Simulatiion 22

Department of Computer Science and Information Technology Deccan Education Society’s

Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

C E R T I F I C A T E

This is to certify that Mr./Miss_________________ of M.Sc Part-I

[COMPUTER SCIENCE] with Seat No._______has successfully

completed the practical of Mobile Computing under my supervision in this

college during the year 2006 - 2007.

Lecturer-in-charge Head of Department ( Mr.Siddhesh Kadam) Dept of Com.Sc and I.T (Dr. Seema Purohit)

Page 3: Mobile Comm-Simulatiion 22

NAAC Accreditation “A” Grade

Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Mobile Computing

I N D E X

No. Title Page No. Date Sign

1 Create an application to draw simple text & perform various operations

2 Create an application to handle multiple forms

3 Create an application to demonstrate timers

4 Create an application to demonstrate use of buffering

5 Create an application to demonstrate bouncing ball

6 Create an application to demonstrate different I / P control

7 Create an application to demonstrate a dialog box

8 Create an application to demonstrate bitmap image

9 Create an application to demonstrate various types of events

Page 4: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 1

P1_1. Introduction to J2ME. Packages Used in Programs:

Package javax.microedition.midlet Description The MIDlet package defines Mobile Information Device Profile applications and

the interactions between the application and the environment in which the application runs.

An application of the Mobile Information Device Profile is a MIDlet. Package javax.microedition.lcdui

The UI API provides a set of features for implementation of user interfaces for MIDP applications.

Classes Used in Programs: Built In public abstract class MIDlet extends Object

A MIDLet is a MID Profile application. The application must extend this class to allow the application management

software to control the MIDlet and to be able to retrieve properties from the application descriptor and notify and request state changes.

The methods of this class allow the application management software to create, start, pause, and destroy a MIDlet.

A MIDlet is a set of classes designed to be run and controlled by the application management software via this interface.

The states allow the application management software to manage the activities of multiple MIDlets within a runtime environment.

It can select which MIDlets are active at a given time by starting and pausing them individually.

The application management software maintains the state of the MIDlet and invokes methods on the MIDlet to change states.

The MIDlet implements these methods to update its internal activities and resource usage as directed by the application management software.

The MIDlet can initiate some state changes itself and notifies the application management software of those state changes by invoking the appropriate methods.

Page 5: Mobile Comm-Simulatiion 22

public class Display extends Object Display represents the manager of the display and input devices of the system. It includes methods for retrieving properties of the device and for requesting that

objects be displayed on the device. Other methods that deal with device attributes are primarily used with Canvas

objects and are thus defined there instead of here. There is exactly one instance of Display per MIDlet and the application can get a

reference to that instance by calling the getDisplay() method.

public abstract class Canvas extends Displayable The Canvas class is a base class for writing applications that need to handle low-

level events and to issue graphics calls for drawing to the display. Game applications will likely make heavy use of the Canvas class. From an application development perspective, the Canvas class is interchangeable

with standard Screen classes, so an application may mix and match Canvas with high-level screens as needed.

For example, a List screen may be used to select the track for a racing game, and a Canvas subclass would implement the actual game.

public class TextBox extends Screen

The TextBox class is a Screen that allows the user to enter and edit text. A TextBox has a maximum size, which is the maximum number of characters that

can be stored in the object at any time (its capacity). This limit is enforced when the TextBox instance is constructed, when the user is

editing text within the TextBox, as well as when the application program calls methods on the TextBox that modify its contents.

The maximum size is the maximum stored capacity and is unrelated to the number of characters that may be displayed at any given time.

The number of characters displayed and their arrangement into rows and columns are determined by the device.

public class Command extends Object

The Command class is a construct that encapsulates the semantic information of an action.

The behavior that the command activates is not encapsulated in this object. This means that command contains only information about "command" not the

actual action that happens when command is activated. The action is defined in a CommandListener associated with the Screen. Command objects are presented in the user interface and the way they are

presented may depend on the semantic information contained within the command.

public abstract class Displayable extends Object

An object that has the capability of being placed on the display. A Displayable object may have commands and listeners associated with it. The contents displayed and their interaction with the user are defined by

subclasses.

Page 6: Mobile Comm-Simulatiion 22

Constructors Used in Programs:

Built In: Public TextBox(String title,String text,int maxSize, int constraints)

Creates a new TextBox object with the given title string, initial contents, maximum size in characters, and constraints.

If the text parameter is null, the TextBox is created empty. The maxSize parameter must be greater than zero.

Command(String label, int commandType, int priority)

Creates a new command object with the given label, type, and priority. Interfaces Used in Programs:

public interface CommandListener This interface is used by applications which need to receive high-level events

from the implementation. An application will provide an implementation of a Listener (typically by using a

nested class or an inner class) and will then provide an instance of it on a Screen in order to receive high-level events on that screen.

Methods Used in Programs:

protected abstract void startApp() throws MIDletStateChangeException Signals the MIDlet that it has entered the Active state. In the Active state the MIDlet may hold resources. The method will only be called when the MIDlet is in the Paused state.

protected abstract void pauseApp()

Signals the MIDlet to stop and enter the Paused state. In the Paused state the MIDlet must release shared resources and become

quiescent. This method will only be called called when the MIDlet is in the Active state.

protected abstract void destroyApp(boolean unconditional) throws MIDletStateChangeException

Signals the MIDlet to terminate and enter the Destroyed state. In the destroyed state the MIDlet must release all resources and save any

persistent state. This method may be called from the Paused or Active states. MIDlets should perform any operations required before being terminated, such as

releasing resources or saving preferences or state. public static Display getDisplay(MIDlet m)

Gets the Display object that is unique to this MIDlet. Parameters m is Midlet of the application.

Page 7: Mobile Comm-Simulatiion 22

It returns the display object that application can use for its user interface and throws NullPointerException if m is null.

public void addCommand(Command cmd) Adds a command to the Displayable. The implementation may choose, for example, to add the command to any of the

available softbuttons or place it in a menu. If the added command is already in the screen (tested by comparing the object

references), the method has no effect. If the Displayable is actually visible on the display, and this call affects the set of

visible commands, the implementation should update the display as soon as it is feasible to do so.

Parameter cmd is the command to be added. Throws NullPointerException if cmd is null.

public void setCommandListener(CommandListener l)

Sets a listener for Commands to this Displayable, replacing any previous CommandListener.

A null reference is allowed and has the effect of removing any existing listener. Parameter l is the new listener, or null.

public void setCurrent(Displayable nextDisplayable)

Requests that a different Displayable object be made visible on the display. The change will typically not take effect immediately. It may be delayed so that it occurs between event delivery method calls, although

it is not guaranteed to occur before the next event delivery method is called. The setCurrent() method returns immediately, without waiting for the change to

take place. Because of this delay, a call to getCurrent() shortly after a call to setCurrent() is

unlikely to return the value passed to setCurrent(). Parameter nextDisplayable is the Displayable requested to be made current; null is

allowed.

public final void notifyDestroyed() Used by an MIDlet to notify the application management software that it has

entered into the Destroyed state. The application management software will not call the MIDlet's destroyApp

method, and all resources held by the MIDlet will be considered eligible for reclamation.

The MIDlet must have performed the same operations (clean up, releasing of resources etc.) it would have if the MIDlet. destroyApp() had been called. protected abstract void paint(Graphics g)

Renders the Canvas. The application must implement this method in order to paint any graphics.

public void setColor(int red,int green,int blue)

Sets the current color to the specified RGB values. All subsequent rendering operations will use this specified color. Parameter red is the red component of the color being set in range 0-255.

Page 8: Mobile Comm-Simulatiion 22

Green is the green component of the color being set in range 0-255. Blue is The blue component of the color being set in range 0-255. Throws IllegalArgumentException if any of the color components are outside of

range 0-255.

public int getWidth() Gets width of the displayable area in pixels. The value is unchanged during the execution of the application and all Canvases

will have the same value. Returns width of the displayable area.

public int getHeight()

Gets height of the displayable area in pixels. The value is unchanged during the execution of the application and all Canvases

will have the same value. Returns height of the displayable area.

public void fillRect(int x,int y,int width,int height)

Fills the specified rectangle with the current color. If either width or height is zero or less, nothing is drawn. Parameter x is the x coordinate of the rectangle to be filled. y is the y coordinate

of the rectangle to be filled. Width is the width of the rectangle to be filled. Height is the height of the rectangle to be filled.

public final void repaint() Requests a repaint for the entire Canvas.

Page 9: Mobile Comm-Simulatiion 22

P1_2. Create an application to display “Hello World” using J2ME. (HelloWorld.java) Classes used: User Defined:

1) HelloWorld: This class is used to display a message hello world in the TextBox . It also implements CommandListener to handle a quit command action

event. PROGRAM: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class HelloWorld extends MIDlet implements CommandListener { private Display display; private TextBox txtBox; private Command quitCommand; public void startApp() { display = Display.getDisplay(this);

txtBox = new TextBox("My First Midlet","Hello World ",40,0); quitCommand = new Command("Quit",Command.SCREEN,0); txtBox.addCommand(quitCommand); txtBox.setCommandListener(this); display.setCurrent(txtBox); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { destroyApp(false); notifyDestroyed(); } } }

Page 10: Mobile Comm-Simulatiion 22

OUTPUT:

Page 11: Mobile Comm-Simulatiion 22

P1_3. Create an application to draw a line & rectangle using J2ME.(DrawShape.java) Classes used: User Defined:

1) DrawShape: It is derived from MIDlet class. This class is used to display two lines & rectangle on the screen. It also uses a canvas derived class for drawing graphics.

2) MyCanvas:

It is derived from Canvas class. This class is used to draw two lines & rectangle on the screen. It also implements command listener to handle the quit command event.

Methods Used:

1) drawLine: public void drawLine(int x1,int y1,int x2,int y2)

Draws a line between the coordinates (x1,y1) and (x2,y2) using the current color and stroke style.

Parameter x1 is the x coordinate of the start of the line, y1 is the y coordinate of the start of the line, x2 is the x coordinate of the end of the line, y2 is the y coordinate of the end of the line.

2) drawRect public void drawRect(int x, int y, int width, int height)

Draws the outline of the specified rectangle using the current color and stroke style.

The resulting rectangle will cover an area (width + 1) pixels wide by (height + 1) pixels tall.

If either width or height is less than zero, nothing is drawn. Parameters: x - the x coordinate of the rectangle to be drawn y - the y coordinate of the rectangle to be drawn width - the width of the rectangle to be drawn height - the height of the rectangle to be drawn

Page 12: Mobile Comm-Simulatiion 22

PROGRAM: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawShape extends MIDlet { private MyCanvas canvas; private Display d; public DrawShape() { canvas = new MyCanvas(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(canvas); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } } class MyCanvas extends Canvas implements CommandListener { private Display display; private Command quitCommand; DrawShape ds; MyCanvas(DrawShape d) { ds = d; display = Display.getDisplay(ds); quitCommand = new Command("Quit",Command.SCREEN,0); addCommand(quitCommand); setCommandListener(this); } public void paint(Graphics g) { g.setColor(255,255,255);

Page 13: Mobile Comm-Simulatiion 22

g.fillRect(0,0,getWidth(),getHeight()); g.setColor(0,0,255); g.drawRect(50,50,150,150); g.drawLine(50,50,200,200); g.drawLine(200,50,50,200); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { ds.exitButton(); } } } OUTPUT:

Page 14: Mobile Comm-Simulatiion 22

P1_4. Create an application to create a button. On click event of this

button, display the rectangle. (ShapeDemo.java) Classes used: User Defined:

1) ShapeDemo: It is derived from MIDlet class. This class is used to display the rectangle on the done button click. It also uses a canvas derived class for drawing rectangle. It also implements command listener to handle the done command event.

3) ShpCanvas: It is derived from Canvas class. This class is used to draw rectangle on the screen. It also implements command listener to handle the quit command event.

PROGRAM: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class ShapeDemo extends MIDlet implements CommandListener { private Display d; public Form form; private Command doneCommand; ShpCanvas canvas; public ShapeDemo() { canvas = new ShpCanvas(this); form = new Form("Rectangle"); doneCommand = new Command("Done",Command.SCREEN,0); form.addCommand(doneCommand); form.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form); } public void pauseApp()

Page 15: Mobile Comm-Simulatiion 22

{ } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == doneCommand) { canvas.isFirstPaint = true; d.setCurrent(canvas); } } } class ShpCanvas extends Canvas implements CommandListener { private Display display; public boolean isFirstPaint = true; private Command quitCommand;

ShapeDemo shp; ShpCanvas(ShapeDemo s) { shp = s; display = Display.getDisplay(shp); quitCommand = new Command("Quit",Command.SCREEN,0); addCommand(quitCommand); setCommandListener(this); } public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); } g.setColor(0,0,255); g.fillRect(50,50,150,150); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) {

Page 16: Mobile Comm-Simulatiion 22

shp.exitButton(); } } } OUTPUT:

Page 17: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 2

Study of the use of different input controls i) Create an application to draw a geometrical figure by using Radio Button

in J2ME. (RadioButtonDemo.java) Classes used: Built In: 1) ChoiceGroup public class ChoiceGroup extends Item implements Choice

A ChoiceGroup is a group of selectable elements intended to be placed within a Form.

The group may be created with a mode that requires a single choice to be made or that allows multiple choices.

The implementation is responsible for providing the graphical representation of these modes and must provide visually different graphics for different modes.

For example, it might use "radio buttons" for the single choice mode and "check boxes" for the multiple choice mode.

User Defined:

1) RadioButtonDemo: It is derived from MIDlet class. This class is used to display the rectangle on selection of Rectangle radio

button and circle on selection of circle radio button . It also uses a canvas derived class for drawing rectangle and circle. It also implements command listener to handle the done command event.

2)ShpCanvas: It is derived from Canvas class. This class is used to draw rectangle on the screen. It also implements command listener to handle the quit command event.

Page 18: Mobile Comm-Simulatiion 22

Methods used: Built In:

1) getString public String getString(int elementNum)

Gets the String part of the element referenced by elementNum. Specified by: getString in interface Choice Parameters: elementNum - the index of the element to be queried Returns: the string part of the element Throws: IndexOutOfBoundsException - if elementNum is invalid

2) getSelectedIndex public int getSelectedIndex()

Returns the index number of an element in the ChoiceGroup that is selected.

For ChoiceGroup objects of type EXCLUSIVE and POPUP there is at most one element selected, so this method is useful for determining the user's choice. Returns -1 if there are no elements in the ChoiceGroup.

For ChoiceGroup objects of type MULTIPLE, this always returns -1 because no single value can in general represent the state of such a ChoiceGroup. To get the complete state of a MULTIPLE Choice, see getSelectedFlags.

Specified by: getSelectedIndex in interface Choice Returns: index of selected element, or -1 if none

3) append public int append(String stringPart, Image imagePart)

Appends an element to the ChoiceGroup. Specified by: append in interface Choice Parameters: stringPart - the string part of the element to be added imagePart - the image part of the element to be added, or null if there is no image part Returns: the assigned index of the element

Page 19: Mobile Comm-Simulatiion 22

Throws: NullPointerException - if stringPart is null

4) drawArc public void drawArc(int x,int y,int width,int height,int startAngle,int arcAngle)

Draws the outline of a circular or elliptical arc covering the specified rectangle, using the current color and stroke style.

The resulting arc begins at startAngle and extends for arcAngle degrees, using the current color. Angles are interpreted such that 0 degrees is at the 3 o'clock position.

A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.

The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments.

The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall. If either width or height is less than zero, nothing is drawn.

The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle.

As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.

Parameters: x - the x coordinate of the upper-left corner of the arc to be drawn y - the y coordinate of the upper-left corner of the arc to be drawn width - the width of the arc to be drawn height - the height of the arc to be drawn startAngle - the beginning angle arcAngle - the angular extent of the arc, relative to the start angle

User Defined:

1) getOptionString(String s) this method is used to get the selected text of the radio buttons using

the methods getstring and getSelectedIndex.

Page 20: Mobile Comm-Simulatiion 22

Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class RadioButtonDemo extends MIDlet implements CommandListener { private Display d; public Form form; private ChoiceGroup shpChoice; private Command doneCommand; private Alert alert; ShapeCanvas canvas; public RadioButtonDemo() { canvas = new ShapeCanvas(this); form = new Form("Select Shape"); shpChoice = new ChoiceGroup("Shape",Choice.EXCLUSIVE); doneCommand = new Command("Done",Command.SCREEN,0); alert = new Alert("My Alert",null,null,AlertType.INFO); shpChoice.append("Rectangle",null); shpChoice.append("Circle",null); form.append(shpChoice); form.addCommand(doneCommand); form.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds)

Page 21: Mobile Comm-Simulatiion 22

{ if(c == doneCommand) { canvas.getOptionString(shpChoice.getString(shpChoice.getSelectedIndex())); canvas.isFirstPaint = true; d.setCurrent(canvas); } } } class ShapeCanvas extends Canvas implements CommandListener { private Display display; public boolean isFirstPaint = true; private Command quitCommand; private Command optionCommand; RadioButtonDemo shp; private String str; ShapeCanvas(RadioButtonDemo s) { shp = s; display = Display.getDisplay(shp); quitCommand = new Command("Quit",Command.SCREEN,0); optionCommand = new Command("Option",Command.BACK,0); addCommand(quitCommand); addCommand(optionCommand); setCommandListener(this); } public void getOptionString(String s) { str = s; } public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); }

Page 22: Mobile Comm-Simulatiion 22

g.setColor(0,0,0); if(str == "Rectangle") g.drawRect(50,50,140,140); if(str == "Circle") g.drawArc(80,80,80,80,0,360); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { shp.exitButton(); } if(c == optionCommand) { display.setCurrent(shp.form); } } }

OUTPUT:

Page 23: Mobile Comm-Simulatiion 22

ii) Create an application to fill the rectangle with the selected colors in

check box in J2ME.(ColorDemo.java)

Classes used: User Defined:

1) ColorDemo: It is derived from MIDlet class. This class is used to fill the rectangle with selected colors. It also uses a canvas derived class for drawing rectangle using selected

colors It gives choice group as multiple ie check boxes to select multiple color

choices. It also implements command listener to handle the done command event.

2) ColorCanvas: It is derived from Canvas class. This class is used to draw rectangle on the screen with selected colors from

the check boxes. It also implements command listener to handle the quit command event. It defines three variables rcol, gcol, bcol to store color values selected

according to red, green and blue colors. Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class ColorDemo extends MIDlet implements CommandListener { private ColorCanvas canvas; private Display d; public Form form; private ChoiceGroup colorChoice; private Command doneCommand; public ColorDemo() {

Page 24: Mobile Comm-Simulatiion 22

canvas = new ColorCanvas(this); form = new Form("Select Color"); colorChoice = new ChoiceGroup("Color",Choice.MULTIPLE); doneCommand = new Command("Done",Command.SCREEN,0); colorChoice.append("Red",null); colorChoice.append("Green",null); colorChoice.append("Blue",null); form.append(colorChoice); form.addCommand(doneCommand); form.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == doneCommand) { if(colorChoice.isSelected(0) == true) canvas.rcol = 255; else canvas.rcol = 0; if(colorChoice.isSelected(1) == true) canvas.gcol = 255; else canvas.gcol = 0; if(colorChoice.isSelected(2) == true) canvas.bcol = 255; else canvas.bcol = 0;

Page 25: Mobile Comm-Simulatiion 22

canvas.isFirstPaint = true; d.setCurrent(canvas); } } } class ColorCanvas extends Canvas implements CommandListener { private Display display; public boolean isFirstPaint = true; public int rcol=0,gcol=0,bcol=0; private Command quitCommand; private Command optionCommand; ColorDemo shp; private String str; ColorCanvas(ColorDemo s) { shp = s; display = Display.getDisplay(shp); quitCommand = new Command("Quit",Command.SCREEN,0); optionCommand = new Command("Option",Command.BACK,0); addCommand(quitCommand); addCommand(optionCommand); setCommandListener(this); } public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); } g.setColor(rcol,gcol,bcol); g.fillRect(20,20,40,40); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { shp.exitButton(); }

Page 26: Mobile Comm-Simulatiion 22

if(c == optionCommand) { display.setCurrent(shp.form); } } } OUTPUT:

Page 27: Mobile Comm-Simulatiion 22

iii) Create an application to change the font style of the defined text in the text box in J2ME.(FontDemo.java)

Classes used: Built In: 1) List public class List extends Screen implements Choice

A Screen containing list of choices. Most of its behavior is common with class ChoiceGroup, and their common

API. The different List types in particular, are defined in interface Choice. When

a List is present on the display, the user can interact with it by selecting elements and possibly by traversing and scrolling among them.

Traversing and scrolling operations do not cause application-visible events. The system notifies the application only when a Command is invoked by

notifying its CommandListener. The List class also supports a select command that may be invoked

specially depending upon the capabilities of the device. The notion of a select operation on a List element is central to the user's

interaction with the List. On devices that have a dedicated hardware "select" or "go" key, the select

operation is implemented with that key. Devices that do not have a dedicated key must provide another means to do

the select operation, for example, using a soft key. The behavior of the select operation within the different types of lists is

described in the following sections. List objects may be created with Choice types of Choice.EXCLUSIVE,

Choice.MULTIPLE, and Choice.IMPLICIT. The Choice type Choice.POPUP is not allowed on List objects.

IMPLICIT Lists can be used to construct menus by providing operations as List elements.

The application provides a Command that is used to select a List element and then defines this Command to be used as the select command.

The application must also register a CommandListener that is called when the user selects or activates the Command:

2) Font public final class Font extends Object

The Font class represents fonts and font metrics. Fonts cannot be created by applications.

Page 28: Mobile Comm-Simulatiion 22

Instead, applications query for fonts based on font attributes and the system will attempt to provide a font that matches the requested attributes as closely as possible.

A Font's attributes are style, size, and face. Values for attributes must be specified in terms of symbolic constants. Values for the style attribute may be combined using the bit-wise OR

operator, whereas values for the other attributes may not be combined. For example, the value STYLE_BOLD | STYLE_ITALIC may be used to

specify a bold-italic font; however SIZE_LARGE | SIZE_SMALL is illegal.

The values of these constants are arranged so that zero is valid for each attribute and can be used to specify a reasonable default font for the system. For clarity of programming, the following symbolic constants are provided and are defined to have values of zero:

• STYLE_PLAIN • SIZE_MEDIUM • FACE_SYSTEM

Values for other attributes are arranged to have disjoint bit patterns in order to raise errors if they are inadvertently misused .However, the values for the different attributes are not intended to be combined with each other.

FACE_SYSTEM public static final int FACE_SYSTEM

The "system" font face. Value 0 is assigned to FACE_SYSTEM.

STYLE_BOLD public static final int STYLE_BOLD

The bold style constant. This may be combined with the other style constants for mixed

styles. Value 1 is assigned to STYLE_BOLD.

STYLE_ITALIC public static final int STYLE_ITALIC

The italicized style constant. This may be combined with the other style constants for mixed styles.

Value 2 is assigned to STYLE_ITALIC.

STYLE_UNDERLINED public static final int STYLE_UNDERLINED

The underlined style constant. This may be combined with the other style constants for mixed styles.

Value 4 is assigned to STYLE_UNDERLINED.

Page 29: Mobile Comm-Simulatiion 22

SIZE_LARGE public static final int SIZE_LARGE

The "large" system-dependent font size. Value 16 is assigned to SIZE_LARGE.

User Defined:

1) FontDemo: It is derived from MIDlet class. This class is used to change the font attributes of the text displayed on the

screen. It also uses a canvas derived class for changing font. It provides the list of font styles like bold, italic, underline etc as

IMPLICIT. It also implements command listener to handle the done command event.

3) FontCanvas: It is derived from Canvas class. This class is used to draw rectangle on the screen with selected colors from

the check boxes. It also implements command listener to handle the quit command event. The option command event is used to display the list of font styles again for

the selection. Uses setFont function of graphics class to set the font of the text as per the

selection of the style in the FontList.

Methods Used: Built In:

1) setFont public void setFont(Font font)

Sets the font for all subsequent text rendering operations. If font is null, it is equivalent to setFont(Font.getDefaultFont()).

Parameters: font - the specified font

Page 30: Mobile Comm-Simulatiion 22

Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class FontDemo extends MIDlet implements CommandListener { private FontCanvas canvas; private Display d; public List fontList; private Command doneCommand; public FontDemo() { canvas = new FontCanvas(this); fontList = new List("Font Style",List.IMPLICIT); doneCommand = new Command("Done",Command.SCREEN,0); fontList.append("Plain",null); fontList.append("Underline",null); fontList.append("Bold",null); fontList.append("Italic",null); fontList.addCommand(doneCommand); fontList.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(fontList); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == doneCommand)

Page 31: Mobile Comm-Simulatiion 22

{ canvas.getOptionString(fontList.getString(fontList.getSelectedIndex())); canvas.isFirstPaint = true; d.setCurrent(canvas); } } } class FontCanvas extends Canvas implements CommandListener { private Display display; public boolean isFirstPaint = true; private Command quitCommand; private Command optionCommand; FontDemo fnt; private String str; FontCanvas(FontDemo f) { fnt = f; display = Display.getDisplay(fnt); quitCommand = new Command("Quit",Command.SCREEN,0); optionCommand = new Command("Option",Command.BACK,0); addCommand(quitCommand); addCommand(optionCommand); setCommandListener(this); } public void getOptionString(String s) { str = s; } public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); } g.setColor(0,0,0); if(str == "Plain")

Page 32: Mobile Comm-Simulatiion 22

g.setFont(Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN,Font.SIZE_LARGE)); if(str == "Underline") g.setFont(Font.getFont(Font.FACE_SYSTEM,Font.STYLE_UNDERLINED,Font.SIZE_LARGE)); if(str == "Bold") g.setFont(Font.getFont(Font.FACE_SYSTEM,Font.STYLE_BOLD,Font.SIZE_LARGE)); if(str == "Italic") g.setFont(Font.getFont(Font.FACE_SYSTEM,Font.STYLE_ITALIC,Font.SIZE_LARGE)); g.drawString("KIRTI",100,90,Graphics.TOP|Graphics.LEFT); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { fnt.exitButton(); } if(c == optionCommand) { display.setCurrent(fnt.fontList); } } }

Page 33: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 3

Create an application to handle multiple forms. (FormDemo.java)

i) Every form must have a Command button to navigate through the forms.

ii) Every form must have a textbox to accept the student information.

Form 1-> Student Name, City, Tel. No.

Form 2-> Stream (Science, Commerce, Arts).

Form 3 -> Student Details from Form 1 and Form 2.

Classes Used:

Built In:

1)TextField public class TextField extends Item

A TextField is an editable text component that may be placed into a Form. It can be given a piece of text that is used as the initial value.

A TextField has a maximum size, which is the maximum number of characters that can be stored in the object at any time (its capacity).

This limit is enforced when the TextField instance is constructed, when the user is editing text within the TextField, as well as when the application program calls methods on the TextField that modify its contents.

The maximum size is the maximum stored capacity and is unrelated to the number of characters that may be displayed at any given time.

The number of characters displayed and their arrangement into rows and columns are determined by the device.

The implementation may place a boundary on the maximum size, and the maximum size actually assigned may be smaller than the application had requested.

The value actually assigned will be reflected in the value returned by getMaxSize().

A defensively-written application should compare this value to the maximum size requested and be prepared to handle cases where they differ.

Page 34: Mobile Comm-Simulatiion 22

User Defined:

1) FormDemo: It is derived from MIDlet class. This class is used to take information from the student in text fields like its

name, telephone number, city and its stream of subjects in radio buttons like arts, science and commerce.

Finally this all information is displayed in the description text field. Also allows navigating between the screens using cmdNextForm1,

cmdNextForm2 and back command buttons. It also implements command listener to handle the all command events.

PROGRAM:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class FormDemo extends MIDlet implements CommandListener { private Display d; public Form form1,form2,form3; private TextField txtName,txtCity,txtTel,txtDesc; private ChoiceGroup chkStream; private Command cmdNextForm1,cmdNextForm2,cmdBack; private String str; private int i; public FormDemo() { form1 = new Form("Personal Info"); form2 = new Form("Educational Info"); form3 = new Form("Student Info"); cmdNextForm1 = new Command("Next",Command.SCREEN,0); cmdNextForm2 = new Command("Next",Command.SCREEN,0); cmdBack = new Command("Back",Command.SCREEN,0); chkStream = new ChoiceGroup("Stream",Choice.EXCLUSIVE); txtName = new TextField("Name",null,50,TextField.ANY); txtCity = new TextField("City",null,50,TextField.ANY); txtTel = new TextField("Tel.",null,50,TextField.ANY);

Page 35: Mobile Comm-Simulatiion 22

txtDesc = new TextField("Info",null,150,TextField.ANY); chkStream.append("Science",null);

chkStream.append("Commerce",null); chkStream.append("Arts",null); form1.append(txtName); form1.append(txtCity); form1.append(txtTel); form1.addCommand(cmdNextForm1); form2.append(chkStream); form2.addCommand(cmdNextForm2); form3.addCommand(cmdBack); form3.append(txtDesc); form1.setCommandListener(this); form2.setCommandListener(this); form3.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form1); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == cmdNextForm1) d.setCurrent(form2); if(c == cmdNextForm2) { str = “Name:"+txtName.getString()+"\n\n"+"City:"+txtCity.getString()+"\n\n" +"Tel.:"+txtTel.getString()+"\n\n"; str=str+"Stream:"+chkStream.getString(chkStream.getSelectedIndex());

Page 36: Mobile Comm-Simulatiion 22

txtDesc.setString(str); d.setCurrent(form3); } if(c == cmdBack) d.setCurrent(form1); } } OUTPUT:

Page 37: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 4

Create an application to demonstrate timers. (Animation. java)

i) Draw a filled rectangle.

ii) Change the color of the rectangle after the specified interval of time.

Classes Used:

Built In:

1) Random public class Random extends Object

An instance of this class is used to generate a stream of pseudorandom numbers.

The class uses a 48-bit seed, which is modified using a linear congruential formula.

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

In order to guarantee this property, particular algorithms are specified for the class Random.

Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code.

However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

2) Math public final class Math extends Object

The class Math contains methods for performing basic numeric operations.

3) Thread public class Thread extends Object implements Runnable

Page 38: Mobile Comm-Simulatiion 22

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of

execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with

lower priority. There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should

override the run method of class Thread. An instance of the subclass can then be allocated and started.

User Defined:

1) AnimDemo: It is derived from MIDlet class. This class is used to change the color of the rectangle at random. It also uses a canvas derived class for changing rectangle color. It also implements command listener to handle the done command event.

4) AnimCanvas: It is derived from Canvas class. This class is used to fill rectangle on the screen with random generated

using Random function and stored in x, y, z variables in paint(). It also implements command listener to handle the quit command event. Creates a thread object and overrides the run function of runnable interface

in which the random numbers are generated. Uses setColor function of graphics class to set the random color of the

Rectangle as reapint() is called.

Methods Used:

Built In:

1) start public void start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

Throws: IllegalThreadStateException - if the thread was already started.

2) sleep public static void sleep(long millis) throws InterruptedException

Page 39: Mobile Comm-Simulatiion 22

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

The thread does not lose ownership of any monitors. Parameters: millis - the length of time to sleep in milliseconds. Throws: InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

3) run public void run()

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

The general contract of the method run is that it may take any action whatsoever.

4) nextInt public int nextInt()

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

The general contract of nextInt is that one int value is pseudorandomly generated and returned.

All 232 possible int values are produced with (approximately) equal probability.

The method nextInt is implemented by class Random as follows: public int nextInt() { return next(32); }

Returns: the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

5) abs public static int abs(int a)

Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Note that if the argument is equal to the value of

Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

Parameters: a - an int value. Returns: the absolute value of the argument.

Page 40: Mobile Comm-Simulatiion 22

PROGRAM:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class AnimDemo extends MIDlet implements CommandListener { private AnimCanvas canvas; private Display d; public Form form; private Command doneCommand; public AnimDemo() { canvas = new AnimCanvas(this); form = new Form("Want to draw Rect"); doneCommand = new Command("Done",Command.SCREEN,0); form.addCommand(doneCommand); form.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == doneCommand) { canvas.isFirstPaint = true; d.setCurrent(canvas); } }

Page 41: Mobile Comm-Simulatiion 22

} class AnimCanvas extends Canvas implements CommandListener,Runnable { private Display display; public boolean isFirstPaint = true; private Command quitCommand; private Command optionCommand; AnimDemo shp; Thread t; Random rand; private int x,y,z; AnimCanvas(AnimDemo s) { shp = s; display = Display.getDisplay(shp); quitCommand = new Command("Quit",Command.SCREEN,0); optionCommand = new Command("Option",Command.BACK,0); addCommand(quitCommand); addCommand(optionCommand); setCommandListener(this); t = new Thread(this); rand = new Random(); t.start(); } public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); } g.setColor(x,y,z); g.fillRect(50,50,140,140); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { shp.exitButton(); } if(c == optionCommand) {

Page 42: Mobile Comm-Simulatiion 22

display.setCurrent(shp.form); } } public void run() { try { x = Math.abs(rand.nextInt()%100); y = Math.abs(rand.nextInt()%100); z = Math.abs(rand.nextInt()%255); repaint(); t.sleep(100); t.run(); }catch(Exception e){} } }

OUTPUT:

Page 43: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 5

Create an application to demonstrate use of buffering (back and double)

i) Draw a circle using a single buffer and

ii) Fill that circle using another buffer.

Classes Used:

Built In:

1) Image public class Image extends Object

The Image class is used to hold graphical image data. Image objects exist independently of the display device.

They exist only in off-screen memory and will not be painted on the display unless an explicit command is issued by the application (such as within the paint() method of a Canvas) or when an Image object is placed within a Form screen or an Alert screen and that screen is made current.

Images are either mutable or immutable depending upon how they are created.

Immutable images are generally created by loading image data from resource bundles, from files, or from the network.

They may not be modified once created. Mutable images are created as blank images containing only white pixels. The application may render on a mutable image by calling getGraphics() on

the Image to obtain a Graphics object expressly for this purpose. Images may be placed within Alert, Choice, Form, or ImageItem objects. The high-level user interface implementation may need to update the

display at any time, without notifying the application. In order to provide predictable behavior, the high-level user interface

objects provide snapshot semantics for the image. That is, when a mutable image is placed within an Alert, Choice, Form, or

ImageItem object, the effect is as if a snapshot is taken of its current contents.

Page 44: Mobile Comm-Simulatiion 22

5) System public final class System extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.

User Defined:

1) BufferDemo: It is derived from MIDlet class. This class is used to change the color of the rectangle at random. It also uses a canvas derived class for changing rectangle color. It also implements command listener to handle the done command event.

6) BufferCanvas: It is derived from Canvas class. This class is used to fill Circle on the screen in paint(). It also implements command listener to handle the quit command event. Creates a thread object and overrides the run function of runnable interface

in which the according to time in millis it changes the image on the screen. It also implements command listener to handle the quit command event.

Methods Used:

Built In:

1) currentTimeMillis public static long currentTimeMillis()

Returns the current time in milliseconds. Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

2) callSerially public void callSerially(Runnable r)

Causes the Runnable object r to have its run() method called later, serialized with the event stream, soon after completion of the repaint cycle.

The call to run() will be serialized along with the event calls into the application.

The run() method will be called exactly once for each call to callSerially().

Calls to run() will occur in the order in which they were requested by calls to callSerially().

If the current Displayable is a Canvas that has a repaint pending at the time of a call to callSerially(), the paint() method of the Canvas

Page 45: Mobile Comm-Simulatiion 22

will be called and will return, and a buffer switch will occur (if double buffering is in effect), before the run() method of the Runnable is called.

If the current Displayable contains one or more CustomItems that have repaints pending at the time of a call to callSerially(), the paint() methods of the CustomItems will be called and will return before the run() method of the Runnable is called. Calls to the run() method will occur in a timely fashion, but they are not guaranteed to occur immediately after the repaint cycle finishes, or even before the next event is delivered.

The callSerially() method may be called from any thread. The call to the run() method will occur independently of the call to callSerially(). In particular, callSerially() will never block waiting for r.run() to return.

The callSerially() facility may be used by applications to run an animation that is properly synchronized with the repaint cycle. A typical application will set up a frame to be displayed and then call repaint(). The application must then wait until the frame is actually displayed, after which the setup for the next frame may occur. The call to run() notifies the application that the previous frame has finished painting.

3) setGrayScale public void setGrayScale(int value)

Sets the current grayscale to be used for all subsequent rendering operations.

For monochrome displays, the behavior is clear. For color displays, this sets the color for all subsequent drawing

operations to be a gray color equivalent to the value passed in. The value must be in the range 0-255.

Parameters: value - the desired grayscale value Throws: IllegalArgumentException - if the gray value is out of range

4) drawImage public void drawImage(Image img, int x, int y, int anchor)

Draws the specified image by using the anchor point. The image can be drawn in different positions relative to the anchor

point by passing the appropriate position constants. If the source image contains transparent pixels, the corresponding

pixels in the destination image must be left untouched. If the source image contains partially transparent pixels, a

compositing operation must be performed with the destination pixels, leaving all pixels of the destination image fully opaque.

Page 46: Mobile Comm-Simulatiion 22

If img is the same as the destination of this Graphics object, the result is undefined. For copying areas within an Image, copyArea should be used instead.

Parameters: img - the specified image to be drawn x - the x coordinate of the anchor point y - the y coordinate of the anchor point anchor - the anchor point for positioning the image Throws: IllegalArgumentException - if anchor is not a legal value NullPointerException - if img is null

Program:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; class BufferCanvas extends Canvas implements Runnable, CommandListener { int degree = 360; long startTime; int seconds; Display display; Image offscreen; private Command quitCommand; BufferDemo bd; BufferCanvas (BufferDemo b,Display display, int seconds) { bd=b; this.display = display; this.seconds = seconds; quitCommand = new Command("Quit",Command.SCREEN,0); addCommand(quitCommand); setCommandListener(this); if (!isDoubleBuffered() && false) { offscreen = Image.createImage(getWidth(),getHeight()); } startTime = System.currentTimeMillis (); } public void paint (Graphics g) { Graphics g2 = offscreen == null ? g : offscreen.getGraphics(); g2.setGrayScale(255); g2.fillRect(0, 0, getWidth(), getHeight());

Page 47: Mobile Comm-Simulatiion 22

if (degree > 0) { g2.setColor (255, 0, 0); g2.fillArc (0,0, getWidth (), getHeight (), 90, degree); display.callSerially (this); } g2.setGrayScale (0); g2.drawArc (0, 0, getWidth ()-1, getHeight ()-1, 0, 360); if (offscreen != null) { g.drawImage (offscreen, 0, 0, Graphics.TOP | Graphics.RIGHT); } } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { bd.exitButton(); } } public void run () { int permille = (int) ((System.currentTimeMillis()- startTime)/seconds); degree = 360 - (permille * 360) / 1000; repaint (); } } public class BufferDemo extends MIDlet { public void startApp () { Display display = Display.getDisplay (this); display.setCurrent (new BufferCanvas (this,display, 10)); } public void pauseApp () {} public void destroyApp (boolean forced) {} public void exitButton() { destroyApp(false); notifyDestroyed(); } }

Page 48: Mobile Comm-Simulatiion 22

OUTPUT:

Page 49: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 6

Demonstration of concept of timer & menu

(GameDemo.java) Create a Game in which a ball bounces in a rectangle using J2ME Create a menu for the above program “ Game” as follows:

Menu ______________ 1. Start / Stop 2. About

Where, Start / Stop menu starts/stops the bouncing of the ball. About menu tells the information about the programmer.

Classes Used:

User Defined: 1) GameDemo:

It is derived from MIDlet class. It also uses a canvas derived class for adding new elements of balls array. Inturn AreaCanvas uses object of ball class.

7) AreaCanvas: It is derived from Canvas class. This class is used to create objects of ball class. It also implements command listener to handle the start,stop and help

command event. keyReleased is overridden to check the status of keys like left, right, up and

down.

Page 50: Mobile Comm-Simulatiion 22

3) Ball

Creates a thread object and overrides the run function of runnable interface in which the according to random numbers generated it draws the circle at random positions on the screen.

On left key creates new object of ball , on right key deletes the previous object of ball , on up key increases the speed and on down key decreases the speed.

For all these this class contains variables like x, y, lastX, lastY, delay=20, rc, gc ,bc and boolean down, right to store the values of ball object last created.

Methods Used:

Built In:

1) setTimeout public void setTimeout(int time)

Set the time for which the Alert is to be shown. This must either be a positive time value in milliseconds, or the

special value FOREVER. Parameters: time - timeout in milliseconds, or FOREVER Throws: IllegalArgumentException - if time is not positive and is not FOREVER

2) getClipX public int getClipX()

Gets the X offset of the current clipping area, relative to the coordinate system origin of this graphics context.

Separating the getClip operation into two methods returning integers is more performance and memory efficient than one getClip() call returning an object.

Returns: X offset of the current clipping area

3) getClipY public int getClipY()

Gets the Y offset of the current clipping area, relative to the coordinate system origin of this graphics context.

Separating the getClip operation into two methods returning integers is more performance and memory efficient than one getClip() call returning an object.

Returns:

Page 51: Mobile Comm-Simulatiion 22

Y offset of the current clipping area

4) getClipWidth public int getClipWidth()

Gets the width of the current clipping area. Returns: width of the current clipping area.

5) getClipWidth public int getClipWidth()

Gets the width of the current clipping area. Returns: width of the current clipping area.

6) getGameAction public int getGameAction(int keyCode)

Gets the game action associated with the given key code of the device.

Returns zero if no game action is associated with this key code. The mapping between key codes and game actions will not change

during the execution of the application. Parameters: keyCode - the key code Returns: the game action corresponding to this key, or 0 if none

7) keyReleased protected void keyReleased(int keyCode)

Called when a key is released. The getGameAction() method can be called to determine what game

action, if any, is mapped to the key. Class Canvas has an empty implementation of this method, and the

subclass has to redefine it if it wants to listen this method. Parameters: keyCode - the key code of the key that was released

Page 52: Mobile Comm-Simulatiion 22

Program:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class GameDemo extends MIDlet { private AreaCanvas canvas; private Display d; public GameDemo() { canvas = new AreaCanvas(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(canvas); canvas.start(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } } class AreaCanvas extends Canvas implements CommandListener { private Display display; private boolean isFirstPaint = true; private Command quitCommand,helpCommand,startCommand; GameDemo gd; Ball ball[]; int balls,i,delay=20; Alert helpAlert; boolean gameStopped=false;

Page 53: Mobile Comm-Simulatiion 22

AreaCanvas(GameDemo g) { gd = g; display = Display.getDisplay(gd); quitCommand = new Command("Quit",Command.SCREEN,0); startCommand = new Command("Start/Stop",Command.SCREEN,0); helpCommand = new Command("Help",Command.SCREEN,0); helpAlert = new Alert("Help","LEFT=Decrease Balls\nRIGHT=Increase Balls\nUP=Increase Speed\nDOWN=Decrease Speed",null,AlertType.INFO); helpAlert.setTimeout(Alert.FOREVER); ball = new Ball[40]; ball[0] = new Ball(this); balls=1; addCommand(quitCommand); addCommand(startCommand); addCommand(helpCommand); setCommandListener(this); } public void paint(Graphics g) { g.setColor(255,255,255); g.fillRect(g.getClipX(),g.getClipY(),g.getClipWidth(),g.getClipHeight()); for(i=0;i<balls;i++) ball[i].paint(g); g.setColor(0,0,0); g.drawRect(0,0,getWidth()-1,getHeight()-1); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { gd.exitButton(); } if(c == helpCommand) { display.setCurrent(helpAlert); } if(c == startCommand) { if(gameStopped==false) { stop();

Page 54: Mobile Comm-Simulatiion 22

gameStopped=true; } else { start(); gameStopped=false; } } } public void start() { Thread t; for(i=0;i<balls;i++) { ball[i].stop = false; t=new Thread(ball[i]); t.start(); } } public void stop() { for(i=0;i<balls;i++) ball[i].stop = true; } public void keyReleased(int keyCode) { int button; button = getGameAction(keyCode); switch(button) { case LEFT: if(balls>0) { ball[balls-1].stop=true; ball[balls-1] = null; balls--; repaint(); } else balls=0; break; case RIGHT: ball[balls] = new Ball(this); new Thread(ball[balls]).start(); balls++;

Page 55: Mobile Comm-Simulatiion 22

break; case UP: if(delay > 0) delay-=10; else delay=0; break; case DOWN: if(delay < 200) delay+=10; else delay=200; break; } } } class Ball implements Runnable { private int i = 0,x,y,lastX,lastY,delay=20,rc,gc,bc; boolean down=true,right=true; AreaCanvas c; boolean stop=false; Random random; Ball(AreaCanvas c) { super(); this.c = c; random = new Random(); lastX=c.getWidth(); lastY=c.getHeight(); x=Math.abs(random.nextInt()%(lastX-10)); y=Math.abs(random.nextInt()%(lastY-10)); rc=Math.abs(random.nextInt()%255); gc=Math.abs(random.nextInt()%255); bc=Math.abs(random.nextInt()%255); } public void paint(Graphics g) { g.setColor(rc,gc,bc); g.fillArc(x,y,10,10,0,360); }

Page 56: Mobile Comm-Simulatiion 22

public void run() { while(!stop) { if(right) x++; else x--; if(down) y++; else y--; if(x==0) right=true; if(x==lastX-10) right=false; if(y==0) down=true; if(y==lastY-10) down=false; c.repaint(x-1,y-1,12,12); try { Thread.sleep(c.delay); } catch(Exception e){} } } }

Page 57: Mobile Comm-Simulatiion 22

OUTPUT:

Page 58: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 7

Demonstration of Dialog Box (AlertDemo.java)

Create an application to take input from user & show it on the Dialog Box using J2ME

Classes Used:

User Defined:

1) Alert Demo:

This class is derived from MIDlet and implements Command Listener.

Has two command buttons back and show.

Provides choices as exclusive for gender male or female and choices as

multiple for qualification SSC, BSC, MSC .

The all description information taken is finally displayed in a text field

as a string.

Methods Used:

Built In:

1) setString public void setString(String str)

Sets the text string used in the Alert. If the Alert is visible on the display when its contents are updated through a

call to setString, the display will be updated with the new contents as soon as it is feasible for the implementation to do so. Parameters: str - the Alert's text string, or null if there is no text

Page 59: Mobile Comm-Simulatiion 22

2) isSelected public boolean isSelected(int elementNum)

Gets a boolean value indicating whether this element is selected. Specified by: isSelected in interface Choice Parameters: elementNum - the index of the element to be queried Returns: selection state of the element Throws: IndexOutOfBoundsException - if elementNum is invalid

Program:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class AlertDemo extends MIDlet implements CommandListener { private Display d; public Form form; private ChoiceGroup genChoice; private ChoiceGroup qualChoice; private Command showCommand; private Command backCommand; private Alert alert; private TextField txtDesc; private String str; private boolean qualCheck[]; private int i; public AlertDemo() { form = new Form("Personal Info"); genChoice = new ChoiceGroup("Gender",Choice.EXCLUSIVE); qualChoice = new ChoiceGroup("Qualification",Choice.MULTIPLE); showCommand = new Command("Show",Command.SCREEN,0); backCommand = new Command("Back",Command.SCREEN,0); txtDesc = new TextField("Description",null,50,TextField.ANY); alert = new Alert("My Alert",null,null,AlertType.WARNING); alert.setTimeout(Alert.FOREVER);

Page 60: Mobile Comm-Simulatiion 22

genChoice.append("Male",null); genChoice.append("Female",null); qualChoice.append("H.S.C.",null); qualChoice.append("B.Sc.",null); qualChoice.append("M.Sc.",null); form.append(genChoice); form.append(qualChoice); form.append(txtDesc); form.addCommand(showCommand); form.setCommandListener(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } public void commandAction(Command c,Displayable ds) { if(c == showCommand) { str = "Gender:"+genChoice.getString(genChoice.getSelectedIndex())+ "\n\n"+"Description:"+txtDesc.getString()+"\n\n"+"Qual:"; for(i=0;i<3;i++) { if(qualChoice.isSelected(i) == true) str = str+qualChoice.getString(i)+","; } alert.setString(str); d.setCurrent(alert); } } }

Page 61: Mobile Comm-Simulatiion 22

OUTPUT:

Page 62: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 8

Demonstration of various graphics objects

1) Colors

i. Create an application to change the background color in

J2ME. (ChangeBgColor.java)

ii. Create an application to change the text color in J2ME.

iii. Create an application to change the background as well as text

color at a time in J2ME.

Classes Used:

User Defined:

1) changeRect:

It is extends MIDlet class.

This class contains the object of MyCanvas1 which changes the color of the

text as well as of the background.

2) MyCanvas1:

This class contains a paint method and a button on click of that button

the color of text and background changes randomly.

Uses the object of Random class to generate the random numbers.

Methods Used:

Built In:

1) drawString public void drawString(String str, int x, int y, int anchor)

Draws the specified String using the current font and color. The x,y position is the position of the anchor point.

Page 63: Mobile Comm-Simulatiion 22

Parameters: str - the String to be drawn x - the x coordinate of the anchor point y - the y coordinate of the anchor point anchor - the anchor point for positioning the text Throws: NullPointerException - if str is null IllegalArgumentException - if anchor is not a legal value

Program:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; public class ChangeRect extends MIDlet { private MyCanvas1 canvas; private Display d; public ChangeRect() { canvas = new MyCanvas1(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(canvas); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } } class MyCanvas1 extends Canvas implements CommandListener { private Display display;

Page 64: Mobile Comm-Simulatiion 22

private Command quitCommand; private Command colorCommand; ChangeRect ds; Random rand; MyCanvas1(ChangeRect d) { ds = d; display = Display.getDisplay(ds); quitCommand = new Command("Quit",Command.SCREEN,0); colorCommand = new Command("Color",Command.BACK,0); rand = new Random(); addCommand(quitCommand); addCommand(colorCommand); setCommandListener(this); } public void paint(Graphics g) {

g.setColor(Math.abs(rand.nextInt()%255), Math.abs(rand.nextInt()%255),Math.abs(rand.nextInt()%255));

g.fillRect(0,0,getWidth(),getHeight()); g.setColor(Math.abs(rand.nextInt()%255), Math.abs(rand.nextInt()%255),Math.abs(rand.nextInt()%255));

g.drawString("Color",getWidth()/2,getHeight()/2,0); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { ds.exitButton(); } if(c == colorCommand) { repaint(); } } }

Page 65: Mobile Comm-Simulatiion 22

OUTPUT:

Page 66: Mobile Comm-Simulatiion 22

P3 (Program).

2) Bitmap

i. Create an application to create a mutable bitmap in J2ME.

Classes Used:

User Defined:

1) MutableImage

It is extends MIDlet class.

This class contains the object of MyCanvas which displays the mutable

image on the screen.

2)MyCanvas:

This class contains a paint method that creates mutable image object.

Uses exitMidlet to close application.

Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MutableImage extends MIDlet { private Display display; private MyCanvas canvas; public MutableImage () { display = Display.getDisplay(this); canvas = new MyCanvas (this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() { } protected void destroyApp( boolean unconditional ) { }

Page 67: Mobile Comm-Simulatiion 22

public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } class MyCanvas extends Canvas implements CommandListener { private Command exit; private MutableImage mutableImage; private Image image = null; public MyCanvas(MutableImage mutableImage) { this. mutableImage = mutableImage; exit = new Command("Exit", Command.EXIT, 1); addCommand(exit); setCommandListener(this); try { image = Image.createImage(70, 70); Graphics graphics = image.getGraphics(); graphics.setColor(255, 0, 0); graphics.fillArc(10, 10, 60, 50, 180, 180); } catch (Exception error) { } } protected void paint(Graphics graphics) { if (image != null) { graphics.setColor(255,255,255); graphics.fillRect(0, 0, getWidth(), getHeight()); graphics.drawImage(image, 60, 40,Graphics.VCENTER | Graphics.HCENTER); } } public void commandAction(Command command, Displayable display) { if (command == exit) { mutableImage.exitMIDlet(); } }

Page 68: Mobile Comm-Simulatiion 22

} } OUTPUT:

Page 69: Mobile Comm-Simulatiion 22

ii) Create an application to create an immutable bitmap in J2ME.

Classes Used:

User Defined:

1) ImmutableImage

It is extends MIDlet class.

This class contains the object of MyCanvas which displays the immutable

image on the screen.

2)MyCanvas:

This class contains a paint method that creates immutable image object.

Uses exitMidlet to close application.

Program:

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImmutableImage extends MIDlet { private Display display; private MyCanvas canvas; public ImmutableImage () { display = Display.getDisplay(this); canvas = new MyCanvas (this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() { } protected void destroyApp( boolean unconditional ) { } public void exitMIDlet() { destroyApp(true);

Page 70: Mobile Comm-Simulatiion 22

notifyDestroyed(); } class MyCanvas extends Canvas implements CommandListener { private Command exit; private ImmutableImage immutableImage; private Image image = null; public MyCanvas(ImmutableImage immutableImage) { this. immutableImage = immutableImage; exit = new Command("Exit", Command.EXIT, 1); addCommand(exit); setCommandListener(this); try { image = Image.createImage("/jc_frame_0.png"); } catch (Exception error) { } } protected void paint(Graphics graphics) { if (image != null) { graphics.setColor(255,255,255); graphics.fillRect(0,0,getWidth(),getHeight()); graphics.drawImage(image, 60, 40,Graphics.VCENTER | Graphics.HCENTER); } } public void commandAction(Command command, Displayable display) { if (command == exit) { immutableImage.exitMIDlet(); } } } }

Page 71: Mobile Comm-Simulatiion 22

OUTPUT:

Page 72: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Mobile Computing

Practical 9

Demonstration of Key Board Event Handling

(TextDemo.java) Create an application that displays characters that you have pressed on the keyboard using J2ME.The characters should be displayed with the help of a canvas.

Classes Used: User Defined:

1) TextDemo : This Class is used to create the TxtCanvas class object to show

keypressed on the keyboard. It also defines a method for exitbutton to destroy an application

which is called in TxtCanvas. 2) TxtCanvas:

This class overrides the method KeyPressed to get the keyCode of the key currently pressed and convert it into character string to be displayed on the screen.

Also contains the quit button to close application. And clear command to clear the screen content.

Methods used: Built In:

1) keyPressed protected void keyPressed(int keyCode)

Called when a key is pressed. Parameters: keyCode - the key code of the key that was pressed

Page 73: Mobile Comm-Simulatiion 22

Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; import java.lang.*; public class TextDemo extends MIDlet { private TxtCanvas canvas; private Display d; public TextDemo() { canvas = new TxtCanvas(this); } public void startApp() { d = Display.getDisplay(this); d.setCurrent(canvas); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void exitButton() { destroyApp(false); notifyDestroyed(); } } class TxtCanvas extends Canvas implements CommandListener { private Display display; private boolean isFirstPaint = true; private Command quitCommand; private Command clearCommand; private String str=""; TextDemo bm; TxtCanvas(TextDemo b) { bm = b; display = Display.getDisplay(bm);

Page 74: Mobile Comm-Simulatiion 22

quitCommand = new Command("Quit",Command.SCREEN,0); clearCommand = new Command("Clear",Command.SCREEN,0); addCommand(quitCommand); addCommand(clearCommand); setCommandListener(this); }

public void paint(Graphics g) { if(isFirstPaint) { isFirstPaint = false; g.setColor(255,255,255); g.fillRect(0,0,getWidth(),getHeight()); } g.setColor(0,0,0); g.drawString(str,0,0,Graphics.TOP|Graphics.LEFT); } protected void keyPressed(int keyCode) { str = str + (char)keyCode; repaint(); } public void commandAction(Command c,Displayable d) { if(c == quitCommand) { bm.exitButton(); } if(c == clearCommand) { isFirstPaint = true; str = ""; repaint(); } } }

Page 75: Mobile Comm-Simulatiion 22

OUTPUT:

Page 76: Mobile Comm-Simulatiion 22

Department of Computer Science and Information Technology Deccan Education Society’s

Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

C E R T I F I C A T E

This is to certify that Mr./Miss_________________ of M.Sc Part-I

[COMPUTER SCIENCE] with Seat No._______has successfully

completed the practical of Simulation & Modeling under my supervision

in this college during the year 2006 - 2007.

Lecturer-in-charge Head of Department (Dr. Seema Purohit) Dept of Com.Sc and I.T (Dr. Seema Purohit)

Page 77: Mobile Comm-Simulatiion 22

NAAC Accreditation “A” Grade

Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Simulation & Modeling

I N D E X

No. Title Page No. Date Sign

1 Single-Channel Queuing Model

2 Multi-Channel Queuing Model

3 Inventory System ( Newspaper Seller’s Problem )

4 Discrete Distribution

5 Continuous Distribution

6 Measure of Performance

7 Generation of Random Numbers

8 Random Numbers Tests

9 Inverse Transform Technique

10 Acceptance – Rejection Technique

Page 78: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical 1

Single – Server Queuing System

1) A small grocery store has only one checkout counter. Customers arrive at

random from 1 to 8 minutes. Each possible value of interarrival time has the same

probability of occurrence. The service times vary from 1 to 6 minutes with the

probabilities shown in following table.

Service-Time distribution.

Service Time (Minutes)

Probability

Cumulative Probability

Random-Digit Assignment

1 0.10 0.10 01-10 2 0.20 0.30 11-30 3 0.30 0.60 31-60 4 0.25 0.85 61-85 5 0.10 0.95 86-95 6 0.05 1.00 96-00 Create the distribution table of inter-arrival time. Give the random numbers to 20

customers and write the Interarrival time and service time duration for the

individual customer according to the random digit range and prepare the

simulation table and analyze the system by simulating the arrival and services of

20 customers. From the table find (i) The average waiting time for a customer. (ii)

The average service time (iii) The average time between arrivals (iv) The average

waiting time for the customer who is waiting. (v) The average time the customer

spends in the system.

(vi) The probabilities that (a) a customer has to wait (b) of an idle server

Page 79: Mobile Comm-Simulatiion 22

2) with the intearrival time distribution for the time from 1 to 10. Give the random

numbers according to the random digit range and prepare the simulation table and

analyze the system by simulating the arrival and services of 20 customers.

3) Taking the same data as that example 1), but now take the service distribution

be

Develop the simulation table & analysis for 20 customers. What is the effect of changing the service-time distribution?

Service Time (Minutes)

1 2 3 4 5 6

Probability 0.05 0.10 0.20 .30 0.25 0.10

Page 80: Mobile Comm-Simulatiion 22

Single-Server Queuing System

1. Data

Page 81: Mobile Comm-Simulatiion 22
Page 82: Mobile Comm-Simulatiion 22

Simulation

Page 83: Mobile Comm-Simulatiion 22

2.Data

Page 84: Mobile Comm-Simulatiion 22
Page 85: Mobile Comm-Simulatiion 22

Simulation

Page 86: Mobile Comm-Simulatiion 22

3.Data

Page 87: Mobile Comm-Simulatiion 22
Page 88: Mobile Comm-Simulatiion 22

Simulation

Page 89: Mobile Comm-Simulatiion 22

Source Code Private Sub CommandButton1_Click() ‘Calculates Inter arrival time & service time an = InputBox("Enter no of arrivals less than or equal to 10", an) If (an = "" Or an > 10) Then Exit Sub End If ac = 0 For i = 1 To an Sheet1.Cells(6 + i, 2) = i 'To fill the Arrival Time AP = 1 / an Sheet1.Cells(6 + i, 3) = AP 'Probability If (ac <> 0) Then Sheet1.Cells(6 + i, 5) = (ac * 1000) + 1 Else Sheet1.Cells(6 + i, 5) = 0 End If ac = ac + AP Sheet1.Cells(6 + i, 4) = ac 'Cummulative Prob If (Sheet1.Cells(6 + i, 4) = 1) Then Sheet1.Cells(6 + i, 6) = 999 Else Sheet1.Cells(6 + i, 6) = ac * 1000 End If Next sn = Val(InputBox("Enter no of service time less than or equal to 6")) If (sn = "" Or sn > 6) Then Exit Sub End If sc = 0 pb = 1 For i = 1 To sn Sheet1.Cells(i + 21, 2) = i If (i <= sn) Then sp = Val(InputBox("Enter Prob( i th service time )")) Sheet1.Cells(i + 21, 3) = sp If (sc <> 0) Then Sheet1.Cells(i + 21, 5) = (sc * 100) + 1 Else Sheet1.Cells(i + 21, 5) = 0 End If sc = sc + sp Sheet1.Cells(i + 21, 4) = sc If (Sheet1.Cells(i + 21, 4) = 1) Then

Page 90: Mobile Comm-Simulatiion 22

Sheet1.Cells(i + 21, 6) = 99 Else Sheet1.Cells(i + 21, 6) = sc * 100 End If End If Next i End Sub Private Sub CommandButton2_Click() ‘Simulation For i = 1 To 20 x = Rnd() * 1000 x = WorksheetFunction.Round(x, 0) Sheet1.Cells(i + 32, 3) = x j = 0 While (Sheet1.Cells(j + 7, 2) <> "") a = Val(Sheet1.Cells(j + 7, 5)) b = Val(Sheet1.Cells(j + 7, 6)) If (x > a And x <= b) Then Sheet1.Cells(i + 32, 4) = Sheet1.Cells(j + 7, 2) End If j = j + 1 Wend Next For i = 1 To 20 x = Rnd() * 100 x = WorksheetFunction.Round(x, 0) Sheet1.Cells(i + 32, 6) = x j = 0 While (Sheet1.Cells(j + 22, 2) <> "") a = Val(Sheet1.Cells(j + 22, 5)) b = Val(Sheet1.Cells(j + 22, 6)) If (x > a And x <= b) Then Sheet1.Cells(i + 32, 7) = Sheet1.Cells(j + 22, 2) End If j = j + 1 Wend Next End Sub

Page 91: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical 2

Multiple – Server Queuing System

1) Consider a drive – in restaurant where carhops take orders and bring food to

the car. There are two carhops A & B. A is better than B and hence gets the

preference if both the carhops are idle. The car arrives according to the

following distribution.

Interarrival Distribution of Cars

Time between Arrivals(Minutes)

Probability

Cumulative Probability

Random-Digit Assignment

1 0.25 0.25 01-25 2 0.40 0.65 26-65 3 0.20 0.85 66-85 4 0.15 1.00 86-00

The distribution of the service time for A is given as follows

Service Time (Minutes)

Probability

Cumulative Probability

Random-Digit Assignment

2 0.30 0.30 01-30 3 0.28 0.58 31-58 4 0.25 0.83 59-83 5 0.17 1.00 84-00

The distribution of the service time for B is given as follows :

Service Time (Minutes)

Probability

Cumulative Probability

Random-Digit Assignment

3 0.35 0.35 01-35 4 0.25 0.60 36-60 5 0.20 0.80 61-80 6 0.20 1.00 81-00

Page 92: Mobile Comm-Simulatiion 22

Develop a simulation & subsequent analysis for 20 service completion and answer the following queries from the simulation table :

What percent of time A & B individually where busy over total service time.?

What percent of arrivals had to wait.?

What is the average waiting time for all the customer.?

What is the average waiting time for the customer who had to wait.?

Draw your conclusion regarding the system and cost of waiting

2) By using above data but the change arriving distribution of cars as follows

Time between Arrivals (Minutes)

0 1 2 3 4

Probability 0.10 0.20 0.35 0.20 0.15

Develop the simulation table and subsequent analysis for the period of 1 hour. What is the effect of changing the arrival distribtion.

3) Using the above data with B getting the preference when both the carhops are idle and the service distribution for A is changed to

Service Time(Minutes) 1 2 3 4 Probability 0.30 0.30 0.25 0.15

Develop a simulation table and subsequent analysis 30 service completion and answer the following queries :

I) What is the effect of B getting the preference.?

II) What would be the effect of adding new employee who works as fast as B

and it will have all left work after A & B.?

Page 93: Mobile Comm-Simulatiion 22

1-1) Interarrival Distribution of Cars Time between Arrivals(Minutes)

Probability Cumulative Probability

Random-Digit Assignment

1 0.25 0.25 01-25 2 0.40 0.65 26-65 3 0.20 0.85 66-85 4 0.15 1.00 86-100 Service Time Distribution for Able Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

2 0.30 0.30 01-30 3 0.28 0.58 31-58 4 0.25 0.83 59-83 5 0.17 1.00 84-100 Service Time Distribution for Baker Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

3 0.35 0.35 01-35 4 0.25 0.60 36-60 5 0.20 0.80 61-80 6 0.20 1.00 81-100 Shortcuts Used: 1) R no for arrival = Random number for Inter Arrival Time 2) IAT = Inter Arrival Time 3) TAT = Total Arrival Time 4) R no for service = Randum number for Service Time 5) STARTT = Start time of Able/Baker 6) SERT = Service Time of Able/Baker 7) ENDT = End Service Time of Able/Baker Formulas Used: 1) TAT = Previous TAT + IAT 2) STARTT of Able =

IF(TAT >= MAX(ENDT of Able)) TAT

ELSE IF(TAT>=MAX(ENDT of Baker))

"" ELSE

IF(MAX(ENDT of Able)>MAX(ENDT of Baker) ""

ELSE

Page 94: Mobile Comm-Simulatiion 22

MIN(MAX(ENDT of Able),MAX(ENDT of Baker)) 3) SERT of Able =

IF(STARTT of Able="") ""

ELSE SERT

4) ENDT of Able =

IF(STARTT of Able="") ""

ELSE STARTT of Able + SERT of Able

5) STARTT of Baker =

IF(STARTT of Able="") IF(TAT>MAX(ENDT of Baker))

TAT ELSE

IF(TAT>MAX(ENDT of Able)) ""

ELSE MIN(MAX(STARTT of Baker),MAX(STARTT of Able))

ELSE ""

6) SERT of Baker =

IF(STARTT of Baker="") ""

ELSE SERT

7) ENDT of Baker =

IF(STARTT of Baker="") ""

ELSE STARTT of Baker + SERT of Baker

8) QUIT of Customer =

IF(STARTT of Able="") IF(STARTT of Baker>TAT)

STARTT of Baker-TAT ELSE

0 ELSE

IF(STARTT of Able>TAT) STARTT of Able -TAT

ELSE 0

Page 95: Mobile Comm-Simulatiion 22

1-2)

Interarrival and Service Time Distribution ABLE BAKER

Cust No

R no for arrival IAT TAT

R no for service SERT STARTT SERT ENDT STARTT SERT ENDT

QUET

1 0 0 95 5 0 5 5 0 2 26 2 2 21 3 2 3 5 0 3 98 4 6 51 3 6 3 9 0 0 90 4 10 92 5 10 5 15 0 5 26 2 12 89 6 12 6 18 0 6 42 2 14 38 3 15 3 18 1 7 74 3 17 13 2 18 2 20 1 8 80 3 20 61 4 20 4 24 0 9 68 3 23 50 4 23 4 27 0

10 22 1 24 49 3 24 3 27 0 11 48 2 26 39 3 27 3 30 1 12 34 2 28 53 4 28 4 32 0 13 45 2 30 88 5 30 5 35 0 14 24 1 31 1 3 32 3 35 1 15 34 2 33 81 4 35 4 39 2 16 63 2 35 53 4 35 4 39 0 17 38 2 37 81 4 39 4 43 2 18 80 3 40 64 5 40 5 45 0 19 42 2 42 1 2 43 2 45 1 20 56 2 44 67 4 45 4 49 1

42 47 49 29 45 10

Page 96: Mobile Comm-Simulatiion 22

1-3) (i)

Percent of time Able were busy over total service time = total service time of Able * 100

end service time of Able = 47 * 100

49 = 95.91% Percent of time Baker were busy over

total service time = total service time of baker * 100 end service time of Able

= 29 * 100 45

= 64.44% (ii)

Percent of arrivals had to wait = number arrivals who wait * 100 numbers of arrivals

= 8 * 100 20

= 40% (iii)

Average waiting time for all customers = total waiting time of customers

numbers of customers = 10

20 = 0.5 (iv)

Average waiting time for all customers who wait = total waiting time of customers who wait

numbers of customers who wait = 10

8 = 1.25

Page 97: Mobile Comm-Simulatiion 22

2-1) Interarrival Distribution of Cars Time between Arrivals(Minutes)

Probability Cumulative Probability

Random-Digit Assignment

0 0.10 0.10 01-10 1 0.20 0.30 11-30 2 0.35 0.65 31-65 3 0.20 0.85 66-85 4 0.15 1.00 86-100 Service Time Distribution for Able Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

2 0.30 0.30 01-30 3 0.28 0.58 31-58 4 0.25 0.83 59-83 5 0.17 1.00 84-100 Service Time Distribution for Baker Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

3 0.35 0.35 01-35 4 0.25 0.60 36-60 5 0.20 0.80 61-80 6 0.20 1.00 81-100

Page 98: Mobile Comm-Simulatiion 22

2-2)

Interarrival and Service Time Distribution ABLE BAKER

Cust No

R no for arrival IAT TAT

R no for service SERT STARTT SERT ENDT STARTT SERT ENDT

QUET

1 0 0 95 5 0 5 5 02 26 1 1 21 3 1 3 4 03 98 4 5 51 3 5 3 8 00 90 4 9 92 5 9 5 14 05 26 1 10 89 6 10 6 16 06 42 2 12 38 3 14 3 17 27 74 3 15 13 2 16 2 18 18 80 3 18 61 4 18 4 22 09 68 3 21 50 4 21 4 25 0

10 22 1 22 49 3 22 3 25 011 48 2 24 39 3 25 3 28 112 34 2 26 53 4 26 4 30 013 45 2 28 88 5 28 5 33 014 24 1 29 1 3 30 3 33 115 34 2 31 81 4 33 4 37 216 63 2 33 53 4 33 4 37 017 38 2 35 81 4 37 4 41 218 80 3 38 64 5 38 5 43 019 42 2 40 1 2 41 2 43 120 56 2 42 67 4 43 4 47 1

42 45 47 31 43 11

Page 99: Mobile Comm-Simulatiion 22

2-3) (i)

Percent of time Able were busy over total service time = total service time of Able * 100

end service time of Able = 45 * 100

47 = 95.74% Percent of time Baker were busy over

total service time = total service time of baker * 100 end service time of Able

= 31 * 100 43

= 72.09% (ii)

Percent of arrivals had to wait = number arrivals who wait * 100 numbers of arrivals

= 8 * 100 20

= 40% (iii)

Average waiting time for all customers = total waiting time of customers

numbers of customers = 11

20 = 0.55 (iv)

Average waiting time for all customers who wait = total waiting time of customers who wait

numbers of customers who wait = 11

8 = 1.375

Page 100: Mobile Comm-Simulatiion 22

3-1) Interarrival Distribution of Cars Time between Arrivals(Minutes)

Probability Cumulative Probability

Random-Digit Assignment

0 0.10 0.10 01-10 1 0.20 0.30 11-30 2 0.35 0.65 31-65 3 0.20 0.85 66-85 4 0.15 1.00 86-100 Service Time Distribution for Baker Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

3 0.35 0.35 01-35 4 0.25 0.60 36-60 5 0.20 0.80 61-80 6 0.20 1.00 81-100 Service Time Distribution for Able Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

1 0.30 0.30 01-30 2 0.30 0.60 31-60 3 0.25 0.85 61-85 4 0.15 1.00 86-100 Service Time Distribution for Checker Service Time (Minutes)

Probability Cumulative Probability

Random-Digit Assignment

3 0.35 0.35 01-35 4 0.25 0.60 36-60 5 0.20 0.80 61-80 6 0.20 1.00 81-100

Page 101: Mobile Comm-Simulatiion 22

3-2)

Interarrival and Service Time Distribution BAKER ABLE

Cust no.

R no for arrival IAT AAT

R no for service STARTT SERT ENDT STARTT SERT ENDT QUET

.. 0 0 95 0 6 6 02 26 1 1 21 1 1 2 03 98 4 5 51 5 2 7 00 90 4 9 92 9 6 15 05 26 1 10 89 10 4 14 06 42 2 12 38 14 2 16 27 74 3 15 13 15 3 18 08 80 3 18 61 18 5 23 09 68 3 21 50 21 2 23 0

10 22 1 22 49 23 4 27 111 48 2 24 39 24 2 26 012 34 2 26 53 26 2 28 013 45 2 28 88 28 6 34 014 24 1 29 1 29 1 30 015 34 2 31 81 31 3 34 016 63 2 33 53 34 4 38 117 38 2 35 81 35 3 38 018 80 3 38 64 38 5 43 019 42 2 40 1 40 1 41 020 56 2 42 67 42 2 44 0

42 39 43 25 44 4

Page 102: Mobile Comm-Simulatiion 22

3-3)

Page 103: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 3

INVENTORY SYSTEM(“The Newspaper Seller’s problem”)

Given : Distribution of Newspapers Demanded

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

Random digit assignment for type of News Day

Accept the probabilities for the three type of news days : Good, Fair, and Poor.

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)

Page 104: Mobile Comm-Simulatiion 22

News Paper Seller’s Problem

Data

Page 105: Mobile Comm-Simulatiion 22

Simulation

Page 106: Mobile Comm-Simulatiion 22

Source Code Private Sub CommandButton1_Click() ‘Generates Table A b = 1 For i = 0 To 6 a = Cells(7 + i, 2) a1 = a * 100 Cells(7 + i, 8) = "'" & Val(b) & "-" & Val(a1) b = a1 + 1 Next i b = 1 For i = 0 To 5 a = Cells(7 + i, 3) a1 = a * 100 Cells(7 + i, 9) = "'" & Val(b) & "-" & Val(a1) b = a1 + 1 Next i b = 1 For i = 0 To 4 a = Cells(7 + i, 4) a1 = a * 100 Cells(7 + i, 10) = "'" & Val(b) & "-" & Val(a1) b = a1 + 1 Next i End Sub Private Sub CommandButton2_Click() ‘Generates Table B b = 1 For i = 0 To 2 a = Cells(18 + i, 3) a1 = a * 100 Cells(18 + i, 9) = "'" & Val(b) & "-" & Val(a1) b = a1 + 1 Next i End Sub

Page 107: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade

Deccan Education Society’s Kirti M. Doongursee College, Dadar, Mumbai-28

Dept. of Computer Science & I.T. M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 4

Discrete Distribution 1) Write a program to find the Probability Mass Function (pmf) -> p( X), mean

- > E ( X ) and Variance -> V( X ), for the Bernouilli Distribution. Accept

the probability of success p from the user and display the value of pmf.

2) Write a program to find the Probability Mass Function (pmf) -> p(X), mean

-> E(X) and variance -> V(X), for the Binomial Distribution. Accept the

probability of success p, no. of trials to achieve the first success is x from

the user and display the value of pmf.

3) Write a program to find the Probability Mass Function (pmf) -> p( X), mean

- > E ( X ) and Variance -> V( X ), for the Geometric Distribution. Accept

the probability of success p, no. of trials n from the user and display the

value of pmf.

4) Write a program to find the Probability Mass Function (pmf) -> p(X), mean

-> p(X) for the Poisson Distribution. Accept the mean and variance from

the user and display the value of pmf. Also find the cumulative Poisson

distribution table.

Page 108: Mobile Comm-Simulatiion 22

Discrete Distribution:

Code: Private Sub cmdBinomial_Click() Binomial.Activate End Sub Private Sub cmdBurnoulli_Click() Burnoulli.Activate End Sub Private Sub cmdGeometric_Click() Geometric.Activate End Sub Private Sub cmdPoisson_Click() Poisson.Activate End Sub

Page 109: Mobile Comm-Simulatiion 22

Code: Dim p, q, x As Integer Private Sub cmdCal_Click() p = Val(InputBox("Enter the probability for success")) Burnoulli.Cells(6, 3) = p Burnoulli.Cells(8, 3) = 1 - p q = 1 - p Burnoulli.Cells(11, 3) = p Burnoulli.Cells(12, 3) = q Burnoulli.Cells(14, 3) = p Burnoulli.Cells(16, 3) = p * q End Sub Private Sub cmdClear_Click() For i = 1 To 20 Range("C1", "C" & i + 1).Clear Next i End Sub

Page 110: Mobile Comm-Simulatiion 22

Binomial Distribution:

Page 111: Mobile Comm-Simulatiion 22

Code: Option Explicit Dim p, q, a, n, x, y, z As Double Dim xfacto, nfacto, xnfacto As Double Dim pmf As Double Dim str As String Dim lb, ub As Integer Private Sub cmdCal_Click() Dim i, j As Integer Dim sum, m, v As Double p = Val(InputBox("Enter the probability for success")) Binomial.Cells(6, 3) = p q = 1 - p Binomial.Cells(8, 3) = q n = Val(InputBox("Enter the no of trial")) Binomial.Cells(12, 3) = n Binomial.Range("c10").Value = x m = n * p Binomial.Cells(17, 3) = p v = n * p * q Binomial.Cells(19, 3) = v MSChart1.RowCount = n + 1 MSChart1.ColumnCount = 1

Page 112: Mobile Comm-Simulatiion 22

MSChart1.Column = 1 For i = 0 To n Range("E" & i + 6).Value = i Range("g6").Formula = "=combin(" & n & "," & i & ")" Range("g7").Formula = "=power(" & p & "," & i & ")" Range("g8").Formula = "=power(" & q & "," & n - i & ")" pmf = Range("g6").Value * Range("g7").Value * Range("g8").Value Range("F" & i + 6).Value = Round(pmf, 5) MSChart1.Row = i + 1 MSChart1.Data = pmf Range("g6:g8").Clear Next i End Sub Private Sub cmdClear_Click() For i = 0 To 25 Range("c1", "C" & i + 1).Clear Next i End Sub Private Sub CommandButton1_Click() lb = Val(InputBox("Lower bound of range")) ub = Val(InputBox("Upper bound of range")) Dim sum As Double Dim i As Integer sum = 0 For i = lb To ub sum = sum + Range("F" & i + 6).Value Next i Range("B26").Value = "P(" & lb & "<= X <=" & ub & ")" Range("C26").Value = Math.Round(sum, 2) End Sub

Page 113: Mobile Comm-Simulatiion 22

Geometric Distribution:

Page 114: Mobile Comm-Simulatiion 22

Code: Dim p, q, a, n, x, y, z As Double Private Sub cmdCal_Click() Dim i, j As Integer Dim sum As Double p = Val(InputBox("Enter the probability for success")) Geometric.Cells(6, 3) = p q = 1 - p Geometric.Cells(8, 3) = q n = Val(InputBox("Enter the no of trial required to get the first sucess")) Geometric.Cells(12, 3) = n MSChart1.RowCount = n MSChart1.ColumnCount = 1 MSChart1.Column = 1 Range("E5", "F100").ClearContents For i = 1 To n Range("E" & i + 6).Value = i

Page 115: Mobile Comm-Simulatiion 22

pmf = q ^ (i - 1) * p Range("F" & i + 6).Value = Round(pmf, 5) MSChart1.Row = i MSChart1.Data = pmf Next i Geometric.Cells(14, 3) = Range("F" & i + 6 - 1).Value Geometric.Cells(16, 3) = 1 / p Geometric.Cells(18, 3) = q / (Math.Sqr(p)) End Sub Private Sub cmdClear_Click() For i = 0 To 25 Range("c1", "C" & i + 1).Clear Next i End Sub Poisson Distribution:

Page 116: Mobile Comm-Simulatiion 22
Page 117: Mobile Comm-Simulatiion 22

Code: Dim mv, x, xfacto, ifacto As Integer Dim pmf, cdf As Double Dim sum Private Sub cmdCal_Click() mv = Val(InputBox("Enter the mean alpha")) Poisson.Cells(6, 3) = mv Poisson.Cells(10, 3) = mv Poisson.Cells(12, 3) = mv x = Val(InputBox("Enter the random number")) Poisson.Cells(8, 3) = x

Page 118: Mobile Comm-Simulatiion 22

MSChart1.RowCount = x + 1 MSChart1.ColumnCount = 1 MSChart1.Column = 1 MSChart2.RowCount = x + 1 MSChart2.ColumnCount = 1 MSChart2.Column = 1 cdf = 0 For i = 0 To x Range("E" & i + 6).Value = i Range("H5").Formula = "=power(" & mv & "," & i & ")" Range("H6").Formula = "=fact(" & i & ")" pmf = Exp(-mv) * Range("H5").Value / Range("H6").Value Range("F" & i + 6).Value = Round(pmf, 5) cdf = cdf + pmf Range("G" & i + 6).Value = Round(cdf, 5) MSChart1.Row = i + 1 MSChart1.Data = pmf MSChart2.Row = i + 1 MSChart2.Data = cdf Next i End Sub Private Sub cmdClear_Click() For i = 0 To 25 Range("C1", "C" & i + 1).Clear Next i End Sub

Page 119: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 5

Continuous Distribution

5) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Uniform Distribution . Accept

the parameters a and b from the user for the random variable X which is

distributed uniformly between a & b.

6) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Exponential Distribution.

Accept from the user the parameter of distribution λ > 0.

7) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Gamma Distribution. Accept

from the parameters of β and θ from the user.

8) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Erlang Distribution. Accept the

order k ( when β = k ) of the distribution and the parameter kθ from the

user.

9) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Normal Distribution. Accept

the mean µ, variance σ2 & the transformation variable

z = t – µ / σ 10) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Weibull Distribution. Accept a

Page 120: Mobile Comm-Simulatiion 22

random variable X with the location parameter v, scale parameter α > 0,

and the shape parameter β >0 from the user.

11) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Triangular Distribution. Accept

parameters a, b, c where a <= b <= c from the user.

12) Write a program to find the Probability Distribution Function (pdf) &

Cumulative Distribution Function ( cdf ) for Lognormal Distribution.

Accept parameters mean µ and variance σ2 from the user.

Page 121: Mobile Comm-Simulatiion 22

Continuous Distribution

Code: Private Sub CommandButton1_Click() Sheet7.Activate End Sub Private Sub CommandButton2_Click() Sheet8.Activate End Sub Private Sub CommandButton3_Click() Sheet6.Activate End Sub Private Sub CommandButton4_Click() Sheet5.Activate End Sub Private Sub CommandButton5_Click() Sheet4.Activate End Sub Private Sub CommandButton6_Click() Sheet3.Activate End Sub

Page 122: Mobile Comm-Simulatiion 22

Uniform Distribution:

Page 123: Mobile Comm-Simulatiion 22

Code: Dim a As Integer Dim b As Integer Private Sub CommandButton1_Click() a = InputBox("Enter a:") b = InputBox("Enter b:") If a <= 0 Or a >= 100 Then MsgBox "Wrong input." Exit Sub End If For i = 1 To 25 'PDF If i >= a And i <= b Then Sheet7.Cells(i + 4, 2) = 1 / (b - a)

Page 124: Mobile Comm-Simulatiion 22

Else Sheet7.Cells(i + 4, 2) = 0 End If 'CDF If i < a Then Sheet7.Cells(i + 4, 3) = 0 End If If a <= i And i < b Then Sheet7.Cells(i + 4, 3) = (i - a) / (b - a) End If If i >= b Then Sheet7.Cells(i + 4, 3) = 1 End If Sheet7.Cells(i + 4, 1) = i Next i MSChart1.RowCount = 25 MSChart1.ColumnCount = 1 MSChart2.RowCount = 25 MSChart2.ColumnCount = 1 MSChart1.Column = 1 MSChart2.Column = 1 For i = 1 To 25 MSChart1.Row = i MSChart1.Data = Sheet7.Cells(i + 4, 2) MSChart2.Row = i MSChart2.Data = Sheet7.Cells(i + 4, 3) Next i End Sub

Page 125: Mobile Comm-Simulatiion 22

Exponential Distribution:

Page 126: Mobile Comm-Simulatiion 22

Code: Dim lamda As Double Dim x As Double Private Sub CommandButton1_Click() lamda = InputBox("Enter lamda:") x = 0 For i = 1 To 40 'PDF If i >= 0 Then Sheet8.Cells(i + 4, 2) = Val(lamda) * Exp(-Val(lamda) * x) Else Sheet8.Cells(i + 4, 2) = 0 End If 'CDF If i >= 0 Then Sheet8.Cells(i + 4, 3) = 1 - Exp(-Val(lamda) * x)

Page 127: Mobile Comm-Simulatiion 22

Else Sheet8.Cells(i + 4, 3) = 0 End If Sheet8.Cells(i + 4, 1) = x x = x + 0.1 Next i MSChart1.ColumnCount = 1 MSChart1.RowCount = 40 'MSChart1 MSChart2.ColumnCount = 1 MSChart2.RowCount = 40 MSChart1.Column = 1 For i = 1 To 40 MSChart1.Row = i MSChart1.Data = Sheet8.Cells(i + 4, 2) Next i MSChart2.Column = 1 For i = 1 To 40 MSChart2.Row = i MSChart2.Data = Sheet8.Cells(i + 4, 3) Next i End Sub

Page 128: Mobile Comm-Simulatiion 22

Normal Distribution:

Page 129: Mobile Comm-Simulatiion 22

Code: Dim mean, variance As Double Dim x, z As Double Private Sub CommandButton1_Click() mean = InputBox("Enter mean:") variance = InputBox("Enter variance:") x = -2 For i = 1 To 40 'PDF Sheet6.Cells(i + 5, 2) = WorksheetFunction.NormDist(x, mean,

variance, False) 'CDF Sheet6.Cells(i + 5, 3) = WorksheetFunction.NormDist(x, mean,

variance, True)

Page 130: Mobile Comm-Simulatiion 22

Sheet6.Cells(i + 5, 1) = Round(x, 1) x = x + 0.1 z = (i - mean) / Sqr(variance) Range("D" & i + 5).Value = z Next i MSChart1.ColumnCount = 1 MSChart1.RowCount = 40 'MSChart1 MSChart2.ColumnCount = 1 MSChart2.RowCount = 40 MSChart1.Column = 1 For i = 1 To 40 MSChart1.Row = Range("D" & i + 5).Value MSChart1.Data = Sheet6.Cells(i + 5, 2) Next i MSChart2.Column = 1 For i = 1 To 40 MSChart2.Row = i MSChart2.Data = Sheet6.Cells(i + 5, 3) Next i End Sub

Page 131: Mobile Comm-Simulatiion 22

Weibull Distribution:

Page 132: Mobile Comm-Simulatiion 22
Page 133: Mobile Comm-Simulatiion 22

Code: Private Sub CommandButton1_Click() Dim a As Double Dim b As Double Dim c As Double a = InputBox("Enter alpha:") b = InputBox("Enter beta:") c = InputBox("Enter neue:") If a <= 0 And b <= 0 Then MsgBox ("wrong output") End If For i = 1 To 20 'PDF If i >= c Then Sheet5.Cells(i + 5, 2) = b / a * ((i / a) ^ (b - 1)) * Exp(-(i / a) ^ b) Sheet5.Cells(i + 5, 3) = 1 / a * (Exp(-(i / a))) Else Sheet5.Cells(i + 5, 2) = 0 Sheet5.Cells(i + 5, 3) = 0 End If Sheet5.Cells(i + 5, 1) = i Next i MSChart1.RowCount = 40 MSChart1.ColumnCount = 1 MSChart1.Column = 1 MSChart2.RowCount = 40 MSChart2.ColumnCount = 1 MSChart2.Column = 1 For i = 1 To 40 MSChart1.Row = i MSChart1.Data = Sheet5.Cells(i + 5, 2) MSChart2.Row = i MSChart2.Data = Sheet5.Cells(i + 5, 3) Next i End Sub

Page 134: Mobile Comm-Simulatiion 22

Triangular Distribution:

Page 135: Mobile Comm-Simulatiion 22
Page 136: Mobile Comm-Simulatiion 22

Code: Dim a As Double Dim b As Double Dim c As Double Private Sub CommandButton1_Click() a = Val(InputBox("enter value of a")) b = Val(InputBox("enter value of b")) c = Val(InputBox("enter value of c")) If a >= b Or b >= c Then MsgBox ("wrong input") End If 'pdf For i = 0 To 20 If a <= i And i <= b Then Sheet4.Cells(i + 4, 2) = 2 * (i - a) / ((b - a) * (c - a)) ElseIf b < i And i <= c Then Sheet4.Cells(i + 4, 2) = 2 * (c - i) / ((c - b) * (c - a)) Else Sheet4.Cells(i + 4, 2) = 0 End If If i <= a Then Sheet4.Cells(i + 4, 3) = 0 ElseIf a < i And i <= b Then Sheet4.Cells(i + 4, 3) = ((i - a) ^ 2) / ((b - a) * (c - a)) ElseIf b < i And i <= c Then Sheet4.Cells(i + 4, 3) = 1 - ((c - i) ^ 2 / ((c - b) * (c - a))) Else Sheet4.Cells(i + 4, 3) = 1 End If

Page 137: Mobile Comm-Simulatiion 22

Sheet4.Cells(i + 4, 1) = i Next i MSChart1.RowCount = 20 MSChart1.ColumnCount = 1 MSChart1.Column = 1 For i = 4 To 20 MSChart1.Row = i - 2 MSChart1.RowLabel = Sheet4.Cells(i, 1) MSChart1.Data = Sheet4.Cells(i, 2) Next i MSChart2.RowCount = 20 MSChart2.ColumnCount = 1 MSChart2.Column = 1 For i = 4 To 20 MSChart2.Row = i - 2 MSChart2.RowLabel = Sheet4.Cells(i, 1) MSChart2.Data = Sheet4.Cells(i, 2) Next i End Sub Private Sub MSChart1_OLEStartDrag(Data As MSChart20Lib.DataObject,

AllowedEffects As Long) End Sub

Page 138: Mobile Comm-Simulatiion 22

Lognormal Distribution

Page 139: Mobile Comm-Simulatiion 22

Code: Dim sig , m, x As Double Dim i As Integer Private Sub CommandButton1_Click() sig = InputBox("Enter variance :") m = InputBox("Enter meue:") x = 0 If Sqr(m) < 0 Then MsgBox ("wrong output") End If For i = 4 To 28 x = x + 0.1 If i > 0 Then Range("B2").Formula = "=ln(" & x & ")" Sheet3.Cells(i, 2) = 1 / ((Sqr(2 * 3.14)) * sig * x) * Exp(- (Range("B2").Value - m) ^ 2) / (2 * (sig ^ 2)) Else Sheet3.Cells(i, 2) = 0 End If Sheet3.Cells(i, 1) = x Next i MSChart1.RowCount = 20 MSChart1.ColumnCount = 1 MSChart1.Column = 1 For i = 4 To 24 MSChart1.Row = Sheet3.Cells(i, 1) MSChart1.Data = Sheet3.Cells(i, 2) Next i End Sub

Page 140: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 6

Measure of Performance

Write a program to simulate a queuing model of the form A/B/C/N/K have their usual meaning and identify Time-Average Number and Average Time Spent in System per Customer.

Page 141: Mobile Comm-Simulatiion 22

Data

Page 142: Mobile Comm-Simulatiion 22
Page 143: Mobile Comm-Simulatiion 22
Page 144: Mobile Comm-Simulatiion 22

Code:

Dim a, lamda, mue, sd, su, LQ, p0, WQ, c, pL, L, pn As Double Dim i As Integer Dim K As Integer Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) c = Val(InputBox("Enter the number of servers:", "Parameters")) K = Val(InputBox("Enter the system capacity:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = c Range("H13").Value = K a = lamda / mue Range("H15").Value = a Dim sum1, sum2 As Double sum1 = 0 sum2 = 0 For i = 0 To c - 1 Range("I15").Formula = "=combin(" & K & "," & i & ")" Range("I16").Formula = "=power(" & a & "," & i & ")" sum1 = sum1 + Range("I15").Value * Range("I16").Value Next i Range("I15").Formula = "=fact(" & K & ")" Range("I18").Formula = "=fact(" & c & ")" For i = c To K Range("I16").Formula = "=power(" & a & "," & i & ")" Range("I17").Formula = "=fact(" & K - i & ")" Range("I19").Formula = "=power(" & c & "," & i - c & ")" sum2 = sum2 + Range("I15").Value * Range("I16").Value / (Range("I17").Value * Range("I18").Value * Range("I19").Value) Next i p0 = 1 / (sum1 + sum2) Range("H17").Value = Round(p0, 3) Range("H20").Value = Round(findPN(K), 3) sum1 = 0 For i = 0 To K sum1 = sum1 + i * findPN(i) Next i Range("H23").Value = Round(sum1, 3) sum1 = 0

Page 145: Mobile Comm-Simulatiion 22

For i = c + 1 To K sum1 = sum1 + (i - c) * findPN(i) Next i Range("H26").Value = Round(sum1, 3) sum1 = 0 For i = 0 To K sum1 = sum1 + (K - i) * lamda * findPN(i) Next i Range("H29").Value = Round(sum1, 3) Range("H31").Value = Round(Range("H23").Value / Range("H29").Value, 3) Range("H34").Value = Round(Range("H26").Value / Range("H29").Value, 3) Range("H37").Value = Round(Range("H29").Value / (c * mue), 3) Range("I15", "I20").ClearContents End Sub Public Function findPN(n As Integer) If n >= 0 And n <= c - 1 Then Range("I15").Formula = "=combin(" & K & "," & n & ")" Range("I16").Formula = "=power(" & a & "," & n & ")" findPN = Range("I15").Value * Range("I16").Value * p0 Else Range("I15").Formula = "=fact(" & K & ")" Range("I16").Formula = "=power(" & a & "," & n & ")" Range("I17").Formula = "=fact(" & K - n & ")" Range("I18").Formula = "=fact(" & c & ")" Range("I19").Formula = "=power(" & c & "," & n - c & ")" findPN = Range("I15").Value * Range("I16").Value * p0 / (Range("I17").Value * Range("I18").Value * Range("I19").Value) End If End Function

Page 146: Mobile Comm-Simulatiion 22

MG1ii :

Dim lamda, mue, sd, su, LQ, p0, WQ As Double Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) sd = Val(InputBox("Enter the Standard deviation:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = sd su = lamda / mue Range("H13").Value = su p0 = 1 - su Range("H21").Value = p0 LQ = (su * su) * (1 + sd * sd * mue * mue) / (2 * p0) Range("H18").Value = LQ Range("H15").Value = su + LQ WQ = lamda * (1 / mue * mue + sd * sd) / (2 * p0) Range("H27").Value = WQ Range("H24").Value = 1 / mue + WQ End Sub

MG1ii :

Dim lamda, mue, sd, su, LQ, p0, WQ, n As Double

Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) n = Val(InputBox("Enter the number of customers:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = 1 / mue su = lamda / mue Range("H13").Value = su Range("H15").Value = su / (1 - su) Range("H18").Value = su * su / (1 - su) Range("H24").Value = 1 / (mue * (1 - su)) Range("H27").Value = su / (mue * (1 - su)) Range("E21").Value = "Probability of having " & n & " customers" Range("I21").Formula = "=power(" & su & "," & n & ")" Range("H21").Value = (1 - su) * Range("I21").Value Range("I21").ClearContents End Sub

Page 147: Mobile Comm-Simulatiion 22

MMcii :

Dim lamda, mue, sd, su, LQ, p0, WQ, n, c, pL, L As Double Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) c = Val(InputBox("Enter the number of servers:", "Parameters")) 'n = Val(InputBox("Enter the number of customers:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = c su = lamda / (c * mue) Range("H13").Value = su Dim sum As Double sum = 0 For i = 0 To c - 1 Range("I15").Formula = "=power(" & lamda / mue & "," & i & ")" Range("I16").Formula = "=fact(" & i & ")" sum = sum + Range("I15").Value * Range("I16").Value Next i Range("I15").Formula = "=power(" & c * su & "," & c & ")" Range("I16").Formula = "=fact(" & c & ")" p0 = Round(1 / (sum + Range("I15").Value * (1 / Range("I16").Value) * (1 / (1 - su))), 5) Range("H15").Value = p0 pL = Round((Range("I15").Value * p0) / (Range("I16").Value * (1 - su)), 5) Range("H18").Value = pL Range("I15").ClearContents Range("I16").ClearContents LQ = (su * pL / (1 - su)) Range("H24").Value = LQ L = c * su + LQ Range("H21").Value = L Range("H27").Value = L / lamda Range("H30").Value = Range("H27").Value - (1 / mue) End Sub

Page 148: Mobile Comm-Simulatiion 22

MGiii :

Dim lamda, mue, sd, su, LQ, p0, WQ, n, c, pL, L As Double Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) c = Val(InputBox("Enter the number of servers:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = c p0 = Exp(-lamda / mue) Range("H15").Value = p0 Dim sum As Double sum = 0 For i = 0 To c Range("I15").Formula = "=power(" & lamda / mue & "," & i & ")" Range("I16").Formula = "=fact(" & i & ")" sum = sum + p0 * Range("I15").Value / Range("I16").Value Next i Range("H18").Value = sum Range("I15").ClearContents Range("I16").ClearContents Range("H21").Value = lamda / mue Range("H24").Value = 0 Range("H27").Value = 1 / mue Range("H30").Value = 0 End Sub

MMcNi :

Dim lamda, mue, sd, su, LQ, p0, WQ, n, c, pL, L As Double Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) c = Val(InputBox("Enter the number of servers:", "Parameters")) n = Val(InputBox("Enter the system capacity:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = c Range("H13").Value = n Range("H15").Value = lamda / mue su = lamda / (c * mue) Range("H17").Value = su Dim sum1, sum2 As Double sum1 = 0

Page 149: Mobile Comm-Simulatiion 22

sum2 = 0 For i = 1 To c Range("I15").Formula = "=power(" & lamda / mue & "," & i & ")" Range("I16").Formula = "=fact(" & i & ")" sum1 = sum1 + Range("I15").Value / Range("I16").Value Next i For i = c + 1 To n Range("I15").Formula = "=power(" & su & "," & i - c & ")" sum2 = sum2 + Range("I15").Value Next i Range("I15").Formula = "=power(" & lamda / mue & "," & c & ")" Range("I16").Formula = "=fact(" & c & ")" p0 = 1 / (1 + sum1 + (Range("I15").Value / Range("I16").Value) * sum2) Range("H19").Value = Round(p0, 3) Range("I15").Formula = "=power(" & lamda / mue & "," & n & ")" Range("I17").Formula = "=power(" & c & "," & n - c & ")" Range("H22").Value = Round(Range("I15").Value * p0 / (Range("I16").Value * (Range("I17").Value)), 3) Range("I15").Formula = "=power(" & lamda / mue & "," & c & ")" 'Range("I16").Formula = "=fact(" & c & ")" Range("I17").Formula = "=power(" & su & "," & n - c & ")" LQ = Round(p0 * Range("I15").Value * su * (1 - Range("I17").Value - (n - c) * Range("I17").Value * (1 - su)) / (Range("I16").Value * (1 - su) * (1 - su)), 3) Range("H25").Value = LQ Range("I15").ClearContents Range("I16").ClearContents Range("I17").ClearContents Range("H28").Value = Round(lamda * (1 - Range("H22").Value), 3) Range("H30").Value = Round(LQ / Range("H28").Value, 3) Range("H33").Value = Round(Range("H30").Value + 1 / mue, 3) Range("H36").Value = Round(Range("H33").Value * Range("H28").Value, 3) End Sub

MMcKK :

Dim a, lamda, mue, sd, su, LQ, p0, WQ, c, pL, L, pn As Double Dim i As Integer Dim K As Integer Private Sub CommandButton1_Click() lamda = Val(InputBox("Enter the Arrival rate (lamda):", "Parameters")) mue = Val(InputBox("Enter the Service rate (mue):", "Parameters")) c = Val(InputBox("Enter the number of servers:", "Parameters"))

Page 150: Mobile Comm-Simulatiion 22

K = Val(InputBox("Enter the system capacity:", "Parameters")) Range("H7").Value = lamda Range("H9").Value = mue Range("H11").Value = c Range("H13").Value = K a = lamda / mue Range("H15").Value = a Dim sum1, sum2 As Double sum1 = 0 sum2 = 0 For i = 0 To c - 1 Range("I15").Formula = "=combin(" & K & "," & i & ")" Range("I16").Formula = "=power(" & a & "," & i & ")" sum1 = sum1 + Range("I15").Value * Range("I16").Value Next i Range("I15").Formula = "=fact(" & K & ")" Range("I18").Formula = "=fact(" & c & ")" For i = c To K Range("I16").Formula = "=power(" & a & "," & i & ")" Range("I17").Formula = "=fact(" & K - i & ")" Range("I19").Formula = "=power(" & c & "," & i - c & ")" sum2 = sum2 + Range("I15").Value * Range("I16").Value / (Range("I17").Value * Range("I18").Value * Range("I19").Value) Next i p0 = 1 / (sum1 + sum2) Range("H17").Value = Round(p0, 3) Range("H20").Value = Round(findPN(K), 3) sum1 = 0 For i = 0 To K sum1 = sum1 + i * findPN(i) Next i Range("H23").Value = Round(sum1, 3) sum1 = 0 For i = c + 1 To K sum1 = sum1 + (i - c) * findPN(i) Next i Range("H26").Value = Round(sum1, 3) sum1 = 0 For i = 0 To K sum1 = sum1 + (K - i) * lamda * findPN(i) Next i Range("H29").Value = Round(sum1, 3) Range("H31").Value = Round(Range("H23").Value / Range("H29").Value, 3)

Page 151: Mobile Comm-Simulatiion 22

Range("H34").Value = Round(Range("H26").Value / Range("H29").Value, 3) Range("H37").Value = Round(Range("H29").Value / (c * mue), 3) Range("I15", "I20").ClearContents End Sub Public Function findPN(n As Integer) If n >= 0 And n <= c - 1 Then Range("I15").Formula = "=combin(" & K & "," & n & ")" Range("I16").Formula = "=power(" & a & "," & n & ")" findPN = Range("I15").Value * Range("I16").Value * p0 Else Range("I15").Formula = "=fact(" & K & ")" Range("I16").Formula = "=power(" & a & "," & n & ")" Range("I17").Formula = "=fact(" & K - n & ")" Range("I18").Formula = "=fact(" & c & ")" Range("I19").Formula = "=power(" & c & "," & n - c & ")" findPN = Range("I15").Value * Range("I16").Value * p0 / (Range("I17").Value * Range("I18").Value * Range("I19").Value) End If End Function

Page 152: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 7

Methods of Generating Random Number Using the examples / data taken in your theory session find the sequence of n

digited random number using

1. Linear congruential method 2. Multiple congruential method 3. Mid square method 4. Combined linear congruential method

Page 153: Mobile Comm-Simulatiion 22

Data :

Main Program:

Code :

Main Program : Private Sub cmdComb_Click() combined.Activate End Sub Private Sub cmdLinear_Click() Linear.Activate End Sub Private Sub cmdMid_Click() MidSquare.Activate End Sub Private Sub cmdmul_Click() multiplicative.Activate End Sub

Page 154: Mobile Comm-Simulatiion 22

Linear : Data:

Chart:

Page 155: Mobile Comm-Simulatiion 22

Code : Linear : Private Sub cmdCal_Click() Dim xo, a, c, m As Double Dim i, h As Integer x0 = Val(InputBox("enter the initial value of x")) a = Val(InputBox("enter the value of constant multiplier a")) c = Val(InputBox("enter the increment value of c")) m = Val(InputBox("enter the modulus value of m")) Range("e" & 5).Value = x0 Range("e" & 7).Value = a Range("e" & 9).Value = c Range("e" & 11).Value = m i = o newRandom: If i = 0 Then x0 = (Range("e7").Value * Range("e5").Value + Range("e9").Value) Mod Range("e11").Value Else x0 = (Range("e7").Value * Range("h" & i + 4).Value + Range("e9").Value) Mod Range("e11").Value End If For h = 0 To i If Linear.Cells(h + 5, 8) = x0 Then MsgBox "Numbers repeated" GoTo printChart End If Next h Linear.Cells(i + 5, 8) = x0 i = i + 1 GoTo newRandom printChart: MSChart1.ColumnCount = i MSChart1.RowCount = 1 MSChart1.RowLabel = "Linear Congruential Method" For h = 1 To i MSChart1.Column = h MSChart1.Data = Linear.Cells(h + 4, 8)

Page 156: Mobile Comm-Simulatiion 22

Next h End Sub Private Sub cmdClear_Click() Range("e5", "e11").ClearContents Range("h5", "h11").ClearContents End Sub

Page 157: Mobile Comm-Simulatiion 22

Multiplicative Congruential Method : Data :

Chart :

Page 158: Mobile Comm-Simulatiion 22

Multiplicative Congruential Method : Program : Private Sub cmdCal_Click() Dim xo, a, m As Double Dim i, h As Integer x0 = Val(InputBox("enter the initial value of x")) a = Val(InputBox("enter the value of constant multiplier a")) m = Val(InputBox("enter the modulus value of m")) Range("e" & 6).Value = x0 Range("e" & 8).Value = a Range("e" & 10).Value = m i = o newRandom: If i = 0 Then x0 = (Range("e8").Value * Range("e6").Value) Mod Range("e10").Value Else x0 = (Range("e8").Value * Range("h" & i + 5).Value) Mod Range("e10").Value End If For h = 0 To i If multiplicative.Cells(h + 6, 8) = x0 Then MsgBox "Numbers repeated" GoTo printChart End If Next h multiplicative.Cells(i + 6, 8) = x0 i = i + 1 GoTo newRandom printChart: MSChart1.ColumnCount = i MSChart1.RowCount = 1 MSChart1.RowLabel = "Multiplicative Congruential Method" For h = 1 To i MSChart1.Column = h MSChart1.Data = multiplicative.Cells(h + 5, 8) Next h End Sub

Page 159: Mobile Comm-Simulatiion 22

Private Sub cmdClear_Click() Range("e5", "e11").ClearContents Range("h5", "h11").ClearContents End Sub Mid Square Method : Data :

Program : Dim rownum As Integer Dim actualNum As Integer Dim sqrNum As Long Dim temp As Long Private Sub cmdCa_Click() End Sub Private Sub cmdCal_Click()

Page 160: Mobile Comm-Simulatiion 22

Dim midDigits, startDigit, EndDigit, x0, k As Integer sqrNum = Range("d14").Value * Range("d14").Value temp = sqrNum midDigits = findDigits(sqrNum) / 2 sqrNum = temp startDigit = midDigits - Range("d9").Value / 2 EndDigit = midDigits + Range("d9").Value / 2 actualNum = Val(Mid(CStr(sqrNum), startDigit + 1, EndDigit - startDigit)) MSChart1.ColumnCount = rownum + 1 MSChart1.RowCount = 1 Range("d14").Value = actualNum MidSquare.Cells(rownum + 6, 7) = actualNum MSChart1.Column = rownum + 1 rownum = rownum + 1 MSChart1.Data = actualNum End Sub Public Function findDigits(num As Long) As Integer findDigits = 0 While num > 0 num = num / 10 findDigits = findDigits + 1 Wend End Function Private Sub cmdClear_Click() Range("d7", "d9").ClearContents Range("g6", "g" & rownum + 6).ClearContents MSChart1.RowCount = 1 MSChart1.ColumnCount = 1 MSChart1.Column = 1 MSChart1.Data = 0 rownum = 0 x0 = Val(InputBox("Enter the initial value : ")) k = Val(InputBox("Enter the value of k : ")) MidSquare.Cells(7, 4) = x0 MidSquare.Cells(9, 4) = k MidSquare.Cells(14, 4) = x0 End Sub

Page 161: Mobile Comm-Simulatiion 22

Combined Linear Congruential Method:

Chart:

Page 162: Mobile Comm-Simulatiion 22

Code:

Private Sub cmdCal_Click() Dim x10, x20, x30, a1, a2, a3, m1, m2, m3 As Double Dim i, k, j As Integer MSChart1.RowCount = Range("d3").Value MSChart1.ColumnCount = 1 If Range("b5").Value = 0 Or Range("c5").Value = 0 Or Range("d5").Value = 0 Then MsgBox "Wrong input " Exit Sub End If If Range("b6").Value = 0 Or Range("c6").Value = 0 Or Range("d6").Value = 0 Then MsgBox "Wrong input " Exit Sub End If If Range("b7").Value = 0 Or Range("c7").Value = 0 Or Range("d7").Value = 0 Then MsgBox "Wrong input " Exit Sub End If For j = 0 To Range("b3").Value combined.Cells(13, j + 1) = combined.Cells(5, j + 1) Next j For j = 1 To Range("d3").Value combined.Cells(13 + j, 1) = j Next j For j = 0 To Range("d3").Value – 1 Sum = 0 For k = 1 To Range("b3").Value Cells(14 + j, k + 1).Value = Cells(6, 1 + k) * Cells(14 + j - 1, k + 1) Mod Cells(7, 1 + k) Sum = Sum + power(k - 1) * Cells(14 + j, k + 1).Value Next k Range("E" & 14 + j).Value = Sum Mod Range("b7").Value

Page 163: Mobile Comm-Simulatiion 22

If Range("E" & 14 + j).Value > 0 Then Range("F" & 14 + j).Value = Range("E" & 14 + j).Value / Range("b7").Value Else Range("F" & 14 + j).Value = (Range("b7").Value - 1) / Range("b7").Value End If MSChart1.Row = j + 1 MSChart1.Column = 1 MSChart1.RowLabel = "R" & j + 1 MSChart1.Data = Range("F" & 14 + j).Value Next j End Sub Private Sub cmdClear_Click() Range("b5", "b7").ClearContents Range("c5", "c7").ClearContents Range("d5", "d7").ClearContents Range("b13", "b" & Range("d3").Value + 13).ClearContents Range("c13", "c" & Range("d3").Value + 13).ClearContents Range("d13", "d" & Range("d3").Value + 13).ClearContents Range("e13", "e" & Range("d3").Value + 13).ClearContents Range("f13", "f" & Range("d3").Value + 13).ClearContents End Sub Private Function power(ByVal pow As Integer) As Integer power = 1 For i = 1 To pow power = power * (-1) Next i End Function

Page 164: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 8

Random Numbers Tests

Write a program to test the Random numbers using 1) Frequency Test

a) Chi – Square test. Accept n random numbers, levels of significance

α, number of intervals n, set of observed values and set of estimated

values.

b) Kolmogorov - Smirnov Test. Accept n random numbers, number of

observation N, the set of observation (Ri) where 1 <= i <= N

2) Runs Test : Accept n random numbers and levels of significance α to reject

or accept the given set of random numbers

a) Runs up and Runs Down Test : Accept the total number of runs a to

find the mean and variance of a

b) 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 fine the mean and variance for b

c) Autocorrelation Test : Accept N random numbers, level of

significance α, the lag m, the starting number i, M such that

i+(M+1)m <= N

Page 165: Mobile Comm-Simulatiion 22

Frequency Test

Output : Chi - Square Method

Page 166: Mobile Comm-Simulatiion 22

Chi-Square Test -: Program : Dim count, count1 As Integer Dim minVal As Double Dim maxVal As Double Dim n1, N, e, z, a As Integer Dim rownum As Integer Private Sub cmdCal_Click() minVal = 0 maxVal = 0.1 For j = 4 To 13 count = 0 For i = 4 To 53 If Sheet1.Cells(i, 1) >= minVal And Sheet1.Cells(i, 1) < maxVal Then count = count + 1 End If Next i Sheet1.Cells(j, 3) = count minVal = minVal + 0.1 maxVal = maxVal + 0.1 Next j count1 = 0

Page 167: Mobile Comm-Simulatiion 22

i = 4 Do Until Sheet1.Cells(i, 1) = "" count1 = count1 + 1 i = i + 1 Loop N = count1 count2 = 0 k = 4 Do Until Sheet1.Cells(k, 2) = "" count2 = count2 + 1 k = k + 1 Loop n1 = count2 For l = 4 To 13 Sheet1.Cells(l, 4) = N / n1 Next l For m = 4 To 13 Sheet1.Cells(m, 5) = (Sheet1.Cells(m, 3) - Sheet1.Cells(m, 4)) * (Sheet1.Cells(m, 3) - Sheet1.Cells(m, 4)) Next m Sheet1.Cells(14, 6) = 0 For y = 4 To 13 Sheet1.Cells(y, 6) = Sheet1.Cells(y, 5) / Sheet1.Cells(y, 4) Sheet1.Cells(14, 6) = Sheet1.Cells(14, 6) + Sheet1.Cells(y, 6) Next y a = Sheet1.Cells(14, 6) z = Val(InputBox("Enter the table value for chi-square ")) If a < z Then MsgBox ("Z is Accepted") Else MsgBox ("Z is Rejected") End If End Sub Private Sub cmdClear_Click() Range("c1", "c" & rownum).ClearContents Range("A4", "A" & rownum).ClearContents Range("D4", "D" & rownum).ClearContents Range("F14").ClearContents Range("E4", "E" & rownum).ClearContents Range("F4", "F" & rownum).ClearContents

Page 168: Mobile Comm-Simulatiion 22

End Sub Private Sub cmdRandom_Click() x = Val(InputBox("Enter the Random Number ( Between 0 & 1)")) rownum = 4 For i = 0 To x Step 0.02 Sheet1.Cells(rownum, 1) = i rownum = rownum + 1 Next i End Sub

Page 169: Mobile Comm-Simulatiion 22

Kolmogorov- Smirnov Test : Data:

Code: Kolmogorov-Smirnov Test : Program : Dim j, k, i, N, m, t1, r As Integer Dim z, max, min, t As Double Private Sub cmdCal_Click() j = 0 k = 0 max = 0 While (Range("A" & j + 7).Value <> "") j = j + 1 Wend For k = 1 To j Kolmogorov.Cells(k + 6, 2) = k Kolmogorov.Cells(k + 6, 3) = Range("A" & k + 6).Value Kolmogorov.Cells(k + 6, 4) = Range("A" & k + 6).Value Next k For k = 1 To j t1 = 0 min = Range("d" & k + 6).Value t = min For m = k + 1 To 6 If Range("d" & m + 5).Value < min Then min = Range("d" & m + 5).Value

Page 170: Mobile Comm-Simulatiion 22

r = m t1 = 1 End If Next m If t1 = 1 Then Kolmogorov.Cells(r + 5, 4) = t Kolmogorov.Cells(k + 6, 4) = min End If Next k For k = 1 To j Kolmogorov.Cells(k + 6, 5) = Val(Range("B" & k + 6).Value / j) Next k For k = 1 To j Kolmogorov.Cells(k + 6, 6) = Val((Range("B" & k + 6).Value - 1) / j) Next k For k = 1 To j Kolmogorov.Cells(k + 6, 7) = Kolmogorov.Cells(k + 6, 5) - Kolmogorov.Cells(k + 6, 4) Next k For k = 1 To j Kolmogorov.Cells(k + 6, 8) = Kolmogorov.Cells(k + 6, 4) - Kolmogorov.Cells(k + 6, 6) Next k For k = 1 To j If Range("G" & k + 6).Value > max Then max = Range("G" & k + 6).Value End If Next k Kolmogorov.Cells(13, 7) = max max = 0 For k = 1 To j If Range("H" & k + 6).Value > max Then max = Range("H" & k + 6).Value End If Next k Kolmogorov.Cells(14, 7) = max If (Range("g13").Value > Range("G14").Value) Then Kolmogorov.Cells(16, 7) = Range("g13").Value Else

Page 171: Mobile Comm-Simulatiion 22

Kolmogorov.Cells(16, 7) = Range("g14").Value End If z = Val(InputBox("Enter the critical value : ")) If (Range("g14").Value < z) Then MsgBox "Accept" Else MsgBox "Reject" End If End Sub

Runs Test Runs Up And Runs Down -: Data:

Page 172: Mobile Comm-Simulatiion 22

Program : Dim i As Integer Private Sub cmdAccept_Click() x = InputBox("Enter the critical value z") If RunUpDown.Cells(11, 5) <= Val(x) Then MsgBox ("Accepted") Else MsgBox ("Rejected") End If End Sub Private Sub cmdClear_Click() For i = 4 To 42 Range("B4", "B" & i + 1).Clear Range("E4", "E" & i + 1).Clear Next i End Sub Private Sub cmdMean_Click() RunUpDown.Cells(7, 5) = (2 * RunUpDown.Cells(3, 5) - 1) / 3 End Sub Private Sub cmdNoRun_Click() Count = 1 For i = 4 To 42 If RunUpDown.Cells(i, 2) = RunUpDown.Cells(i + 1, 2) Then Count = Count Else: Count = Count + 1 End If Next i RunUpDown.Cells(5, 5) = Count End Sub Private Sub cmdRun_Click() For i = 4 To 42 If RunUpDown.Cells(i, 1) < RunUpDown.Cells(i + 1, 1) Then RunUpDown.Cells(i, 2) = "1" Else RunUpDown.Cells(i, 2) = "0" End If Next i End Sub

Page 173: Mobile Comm-Simulatiion 22

Private Sub cmdSigma_Click() RunUpDown.Cells(9, 5) = (16 * RunUpDown.Cells(3, 5) - 29) / 90 End Sub Private Sub cmdZ0_Click() RunUpDown.Range("f9").Formula = "=sqrt(e9)" RunUpDown.Cells(11, 5) = (RunUpDown.Cells(5, 5) - RunUpDown.Cells(7, 5)) / RunUpDown.Cells(9, 6) End Sub

Page 174: Mobile Comm-Simulatiion 22

Runs- Above and Below

Data:

Page 175: Mobile Comm-Simulatiion 22

Run Above and Run Below mean test -: Program : Private Sub CommandButton1_Click() For i = 4 To 43 If Sheet2.Cells(i, 1) > Sheet2.Cells(3, 5) Then Sheet2.Cells(i, 2) = 1 Else Sheet2.Cells(i, 2) = 0 End If Next i End Sub Private Sub CommandButton2_Click() Count = 0 For i = 4 To 43 If Sheet2.Cells(i, 2) = 1 Then Count = Count + 1 Else Count = Count End If Next i Sheet2.Cells(6, 5) = Count End Sub Private Sub CommandButton3_Click() Count = 0 For i = 4 To 43 If Sheet2.Cells(i, 2) = 0 Then Count = Count + 1 Else Count = Count End If Next i Sheet2.Cells(8, 5) = Count End Sub Private Sub CommandButton4_Click() Count = 1 For i = 4 To 42 If Sheet2.Cells(i, 2) = Sheet2.Cells(i + 1, 2) Then Count = Count Else: Count = Count + 1 End If Next i

Page 176: Mobile Comm-Simulatiion 22

Sheet2.Cells(10, 5) = Count End Sub Private Sub CommandButton5_Click() Sheet2.Cells(12, 5) = (2 * Sheet2.Cells(6, 5) * Sheet2.Cells(8, 5) / Sheet2.Cells(4, 5)) + (1 / 2) End Sub Private Sub CommandButton6_Click() Sheet2.Cells(14, 5) = (2 * Sheet2.Cells(6, 5) * Sheet2.Cells(8, 5) * (2 * Sheet2.Cells(6, 5) * Sheet2.Cells(8, 5) - Sheet2.Cells(4, 5)) / (Sheet2.Cells(4, 5) * Sheet2.Cells(4, 5) * (Sheet2.Cells(4, 5) - 1))) ^ 0.5 End Sub Private Sub CommandButton7_Click() Sheet2.Cells(16, 5) = (Sheet2.Cells(10, 5) - Sheet2.Cells(12, 5)) / Sheet2.Cells(14, 5) End Sub Private Sub CommandButton8_Click() z = InputBox("Enter the critical value z") If Sheet1.Cells(16, 5) <= Val(z) Then MsgBox ("Accepted") Else MsgBox ("Rejected") End If End Sub Private Sub CommandButton9_Click() For i = 4 To 42 Range("B4", "B" & i + 1).Clear Range("E4", "E" & i + 1).Clear Next i End Sub

Page 177: Mobile Comm-Simulatiion 22

AutoCorrelation:

Data:

Program : 'Option Explicit Dim l As Integer Dim M As Integer Dim sum As Double Private Sub cmdInput_Click() n = Val(InputBox("Enter the total no.N=")) AutoCo.Cells(3, 4) = Val(n) i = Val(InputBox("Enter the starting no.i="))

Page 178: Mobile Comm-Simulatiion 22

AutoCo.Cells(5, 4) = Val(i) l = Val(InputBox("Enter the lag l=")) AutoCo.Cells(7, 4) = Val(l) M = (Val(n) - Val(i) - Val(l)) / Val(l) AutoCo.Cells(9, 4) = Val(M) sum = 0 For k = 0 To Val(M) sum = sum + AutoCo.Cells(Val(i) + k * Val(l), 1) * AutoCo.Cells(Val(i) + (k + 1) * Val(l), 1) Next k r = ((1 / (Val(M) + 1) * sum) - 0.25) AutoCo.Cells(11, 4) = Val(r) s = ((13 * Val(M) + 7) ^ 0.5) / (12 * (Val(M) + 1)) AutoCo.Cells(13, 4) = Val(s) Zo = Val(r) / Val(s) AutoCo.Cells(15, 4) = Val(Zo) End Sub Private Sub cmdAR_Click() z = InputBox("Enter the critical value z") If AutoCo.Cells(15, 4) <= Val(z) Then MsgBox ("Accepted") Else MsgBox ("Rejected") End If End Sub Private Sub cmdClear_Click() For i = 3 To 16 Range("D3", "D" & i + 1).Clear Next i End Sub

Page 179: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 9

Inverse Transform Technique

Write a program to find the Random variates using Inverse Transform

Technique for given Cumulative Distribution Function (cdf) from

the distributions mentioned in practical no. 4.

Page 180: Mobile Comm-Simulatiion 22

Inverse Transform Technique

Code:

Private Sub CommandButton1_Click()

Sheet2.Activate

End Sub

Private Sub CommandButton2_Click()

Sheet3.Activate

End Sub

Private Sub CommandButton3_Click()

Sheet4.Activate

End Sub

Private Sub CommandButton4_Click()

Sheet5.Activate

End Sub

Private Sub CommandButton5_Click()

Sheet6.Activate

End Sub

Page 181: Mobile Comm-Simulatiion 22

Uniform Distribution:

Page 182: Mobile Comm-Simulatiion 22

Code:

Dim a, b, no, i As Integer Dim m, x As Double Private Sub CommandButton1_Click() a = Val(InputBox("Enter the value for a")) Cells(6, 4) = a b = Val(InputBox("Enter the mean value for b")) Cells(8, 4) = b no = Val(InputBox("Enter the no of values required")) Cells(10, 4) = no m = 0 For i = 1 To no Range("D" & i + 14).Formula = "=round(rand(),5)" Range("C" & i + 14).Value = i m = Range("D" & i + 14).Value x = a + (b - a) * m Cells(14 + i, 5) = x Next i End Sub

Page 183: Mobile Comm-Simulatiion 22

Exponential Distribution:

Page 184: Mobile Comm-Simulatiion 22

Code:

Dim mean As Integer

Dim no, i As Integer

Dim m, x As Double

Private Sub CommandButton1_Click()

mean = Val(InputBox("Enter the mean value"))

Cells(6, 4) = mean

no = Val(InputBox("Enter the no of values required"))

Cells(8, 4) = no

m = 0

For i = 1 To no

Range("D" & i + 13).Formula = "=round(rand(),5)"

Range("C" & i + 13).Value = i

m = Range("D" & i + 13).Value

x = -((1 / mean) * (Math.Log(1 - m)))

Cells(13 + i, 5) = x

Next i

End Sub

Page 185: Mobile Comm-Simulatiion 22

Weibull Distribution:

Page 186: Mobile Comm-Simulatiion 22

Code:

Dim alpha, beta, no, i As Integer Dim m, x As Double Private Sub CommandButton1_Click() alpha = Val(InputBox("Enter the value for alpha")) Cells(6, 4) = alpha beta = Val(InputBox("Enter the mean value for beta")) Cells(8, 4) = beta no = Val(InputBox("Enter the no of values required")) Cells(10, 4) = no m = 0 For i = 1 To no Range("D" & i + 12).Formula = "=round(rand(),5)" Range("C" & i + 12).Value = i m = Range("D" & i + 12).Value Cells(12 + i, 4) = m x = alpha * (-(Math.Log(1 - m))) ^ (1 / beta) Cells(12 + i, 5) = x Next i End Sub

Page 187: Mobile Comm-Simulatiion 22

Triangular Distribution:

Code:

Dim no, i, j As Integer Dim r, x, y As Double Private Sub CommandButton1_Click() no = Val(InputBox("Enter the no of values required")) Cells(6, 4) = no r = 0 For i = 1 To no Range("D" & i + 12).Formula = "=round(rand(),5)" Range("C" & i + 12).Value = i r = Range("D" & i + 12).Value If (0 <= r And r <= 0.5) Then x = Math.Sqr(2 * r) End If

Page 188: Mobile Comm-Simulatiion 22

If (0.5 <= r And r <= 1) Then x = 2 - (Math.Sqr(2 * (1 - r))) End If If (r > 1) Then x = 0 MsgBox ("Invalid") End If Cells(12 + i, 5) = x Next i End Sub

Empirical Continuous:

Page 189: Mobile Comm-Simulatiion 22
Page 190: Mobile Comm-Simulatiion 22

Code:

Dim f(20) As Double Dim p(20) As Double Dim c(20) As Double Dim c_i(20) As Double Dim a(20) As Double Private Sub CommandButton1_Click() If TextBox1.Text = "" Then MsgBox "Please enter value of n" Exit Sub ElseIf TextBox3.Text = "" Then MsgBox "Please enter value of upper limit" Exit Sub ElseIf TextBox2.Text = "" Then MsgBox "Please enter value of lower limit" Exit Sub ElseIf TextBox4.Text = "" Then MsgBox "Please enter value of R" Exit Sub End If nci = Val(TextBox1.Text) u = Val(TextBox3.Text) l = Val(TextBox2.Text) r = Val(TextBox4.Text) 'add freq. For i = 0 To nci - 1 f(i) = InputBox("Enter " & i & " th frequency ") Sheet6.Cells(i + 6, 8) = f(i) 'find total freq. s = s + f(i) Next Sheet6.Cells(nci + 7, 8) = s 'Prob p(i) For i = 0 To nci - 1 p(i) = f(i) / s Sheet6.Cells(i + 6, 9) = p(i) Next 'Cumm. freq. c(i) c(0) = p(0)

Page 191: Mobile Comm-Simulatiion 22

For i = 1 To nci - 1 c(i) = c(i - 1) + p(i) Next For i = 0 To nci - 1 Sheet6.Cells(i + 6, 10) = c(i) Next c_i(0) = l Count = (u - l) / nci For i = 0 To nci - 1 c_i(i + 1) = c_i(i) + Count Sheet6.Cells(i + 6, 6) = c_i(i) Sheet6.Cells(i + 6, 7) = c_i(i + 1) Next a(0) = (c_i(1) - c_i(0)) / c(0) For i = 1 To nci - 1 a(i) = (c_i(i + 1) - c_i(i)) / (c(i) - c(i - 1)) Next For i = 0 To nci - 1 Sheet6.Cells(i + 6, 11) = a(i) Next For i = 1 To nci - 1 If (r > c_i(i - 1) & r <= c_i(i)) Then k = c_i(i - 1) + (a(i) * (r - c(i - 1))) End If Next Sheet6.Cells(13, 4) = k End Sub Private Sub CommandButton2_Click() TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox4.Text = "" Sheet6.Cells(13, 4) = "" i = 6 While (Sheet6.Cells(i, 6) <> "") Sheet6.Cells(i, 6) = "" Sheet6.Cells(i, 7) = "" Sheet6.Cells(i, 8) = "" Sheet6.Cells(i, 9) = ""

Page 192: Mobile Comm-Simulatiion 22

Sheet6.Cells(i, 10) = "" Sheet6.Cells(i, 11) = "" i = i + 1 Wend Sheet6.Cells(i + 1, 8) = "" Sheet1.Activate End Sub

Page 193: Mobile Comm-Simulatiion 22

Roll No: 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Simulation & Modeling

Practical No. 10

Acceptance Rejection Technique

Write a program to implement Acceptance – Rejection Technique for a given Distribution (Poisson or Gamma distribution ).

Page 194: Mobile Comm-Simulatiion 22

Code:

Private Sub cmdGamma_Click() Sheet3.Activate End Sub Private Sub cmdpoisson_Click() Sheet2.Activate End Sub

Page 195: Mobile Comm-Simulatiion 22

Poisson Distribution:

Code: Dim r(100) As Double Dim p, oldp Private Sub cmdcal_Click() If txtn.Text = "" Then MsgBox "Please enter value of n" Exit Sub ElseIf txtl.Text = "" Then MsgBox "Please enter value of lamda" Exit Sub End If N = Val(txtn.Text) l = Val(txtl.Text) n1 = 0 p = 1 e = Exp(-l) For i = 0 To N - 1 Sheet2.Cells(i + 6, 5) = n1 r(i) = Rnd() Sheet2.Cells(i + 6, 6) = r(i) oldp = p p = p * r(i) Sheet2.Cells(i + 6, 7) = p Sheet2.Cells(i + 6, 8) = e If p < e Then

Page 196: Mobile Comm-Simulatiion 22

Sheet2.Cells(i + 6, 9) = "Accept" Sheet2.Cells(i + 6, 10) = "N = " & n1 p = oldp Else Sheet2.Cells(i + 6, 9) = "Reject" Sheet2.Cells(i + 6, 10) = "" p = oldp * r(i) n1 = n1 + 1 End If Next End Sub Private Sub cmdclr_Click() txtl.Text = "" txtn.Text = "" i = 6 While (Sheet2.Cells(i, 5) <> "") Sheet2.Cells(i, 5) = "" Sheet2.Cells(i, 6) = "" Sheet2.Cells(i, 7) = "" Sheet2.Cells(i, 8) = "" Sheet2.Cells(i, 9) = "" Sheet2.Cells(i, 10) = "" i = i + 1 Wend Sheet1.Activate End Sub

Page 197: Mobile Comm-Simulatiion 22

Gamma Distribution:

Code: Private Sub cmdcal_Click() If txtb.Text = "" Then MsgBox "Please enter value of beta" Exit Sub ElseIf txtt.Text = "" Then MsgBox "Please enter value of theta" Exit Sub ElseIf txtn.Text = "" Then MsgBox "Please enter value of n" Exit Sub End If N = Val(txtn.Text) bt = Val(txtb.Text) tht = Val(txtt.Text) a = 1 / (((2 * bt) - 1) ^ 0.5) b = bt - WorksheetFunction.Ln(4) For i = 0 To N - 1 Sheet3.Cells(i + 6, 6) = a Sheet3.Cells(i + 6, 7) = b r1 = Rnd() r2 = Rnd()

Page 198: Mobile Comm-Simulatiion 22

Sheet3.Cells(i + 6, 8) = r1 Sheet3.Cells(i + 6, 9) = r2 v = r1 / (1 - r1) x = bt * (v ^ a) Sheet3.Cells(i + 6, 10) = x c = b + ((bt * a) + 1) * (WorksheetFunction.Ln(v) -

WorksheetFunction.Ln(r1 ^ 2 * r2)) Sheet3.Cells(i + 6, 11) = c If x > c Then Sheet3.Cells(i + 6, 12) = "Reject" Else Sheet3.Cells(i + 6, 12) = "Accept" End If x = x / (bt * tht) Next End Sub Private Sub cmdclr_Click() txtb.Text = "" txtn.Text = "" txtt.Text = "" i = 6 While (Sheet3.Cells(i, 6) <> "") Sheet3.Cells(i, 6) = "" Sheet3.Cells(i, 7) = "" Sheet3.Cells(i, 8) = "" Sheet3.Cells(i, 9) = "" Sheet3.Cells(i, 10) = "" Sheet3.Cells(i, 11) = "" Sheet3.Cells(i, 12) = "" i = i + 1 Wend Sheet1.Activate End Sub