Time-step Simulationsdc/CSI110/lect/Fal06lect18.pdf · What synchronized means in Java Suppose one...

21
Time-step Simulation Model: “a simplified representation of something else.” (Java book) The model will SIMULATE something else. Time-step Simulation: We simulate continuous time by a loop. Each iteration of the loop is called a time-step and models an interval of time (like 1 second, 1/100 second, 1 hour, etc.) Like animation or movies: step length 1/15-1/24 second.

Transcript of Time-step Simulationsdc/CSI110/lect/Fal06lect18.pdf · What synchronized means in Java Suppose one...

Time-step Simulation● Model: “a simplified representation of

something else.” (Java book)● The model will SIMULATE something else.● Time-step Simulation: We simulate continuous

time by a loop.● Each iteration of the loop is called a time-step

and models an interval of time (like 1 second, 1/100 second, 1 hour, etc.)

● Like animation or movies: step length 1/15-1/24 second.

What's done in each step● The loop block calculates approximately what

happens in the world during the corresponding time step.

● Projectile motion (ball throwing, etc): in a time-step,1) The ball MOVES (changes position), because its

velocity (speeds in the Up, Right, and Forward directions) is not zero.

2) The ball's downward velocity CHANGES, because of the effect of gravity.

Details● How long is the time-step?

– 1.0/(steps per second) [time unit is seconds]● How much does it move? ( * means multiply)

– right: velocityRight * (1.0/steps per second) [meters]– fwd: velocityForward * (1.0/steps per second)– up: velocityUp * (1.0/steps per second)

● Program it in Alice?– ball.move( Right, velocityRight /steps per second),

duration=(1.0/steps per second), style=ABRUPTLY)– ditto for Forward and Up.

What's the difference between velocity and speed?

Velocity is like speed since it meansthe amount of distance something moves during 1 second.

But, velocity takes into account the DIRECTION of motion. We must specify separately the 3 distances in Up, Right and Forward directions.

More Details● How much do the velocities change during one

time-step?● velocityForward and velocityRight don't change.

– Newton's first law, and our model simplifies away friction against the air.

● velocityUp is reducedvelocityUp set value to (velocityUp – (9.8 * (1.0/(steps per second) )– Newton's 2nd law, acceleration of gravity, & again,

we simplify away friction against air.● 1.0/(steps per second) = seconds per step

What is acceleration of gravity?● Near the surface of the Earth, gravity makes

freely falling objects accelerate at the rate of9.8 (meters per second) per second– in each second, the velocity increases downwardly

by 9.8 meters per second.– in other words, the downward velocity, expressed in

meters per second, changes, during each second, by adding 9.8

– 9.8 is the “change in velocity” that occurs during each second, so its units are

[meters per second per second] = [meters/sec2]

BUT (we have a problem or 2..)

● velocityUp should change all throughout the time of one time step, but the

move up velocityUp/stepsPerSecond duration 1.0/stepsPerSecond style=abruptly

instruction uses constant velocityUp● What happens when ball meets the ground?Well... it's just a MODEL, it simplifies reality, it

has simulation errors.First error can be reduced by using smaller time

steps; that is, more steps per second.

Other refinements● I enhanced the simulation so

1)the ball bounces (velocityUP set to 0 - velocityUp)2)the ball loses speed by 75% or so on each bounce.

● Problem: velUp = velUp – (9.8/(steps per sec.)) is too inaccurate when ball is nearly stationary. I fixed the animation with special case decision making.

● On can also add air friction effects..viscous (honey-like) friction is approximated by

Force opposing motion = Constant * Velocity

Back to Java...

import wheels.users.*;

public class SunCartoon extends Frame {

private Ellipse _sun;private ConversationBubble _bubble;public synchronized void myPause(long milliseconds){

try { wait(milliseconds);

} catch (InterruptedException e) {}}public SunCartoon(){

_sun = new Ellipse(java.awt.Color.YELLOW);_bubble = new ConversationBubble("Here is My Sun, Sunny");

}public void DoAnim(){ int nDots = 35;

Ellipse [] array = new Ellipse[nDots];for( int i = 0; i<nDots; i++){

array[i] = new Ellipse(java.awt.Color.GREEN);array[i].setSize(10,10);array[i].setLocation(20 + 12*i, 20 + 11*i);//The creation and positioning of the green dots is //animated by making the program pause after each dot change._bubble.setLocation(_bubble.getXLocation()+1,

_bubble.getYLocation()); myPause(200);

}

import wheels.users.*;

public class SunCartoon extends Frame {

SunCartoon is a class. ==stamp for object creation.

Every instance of a SunCartoon INHERITS all the properties (data)and methods from some instance of a Frame.

The Frame class is defined in the package wheels.users

The import statement enables us to not bother writing wheels.users.Frame

public means code anywhere can use SunCartoons

import wheels.users.*;public class SunCartoon extends Frame {

private Ellipse _sun;private ConversationBubble _bubble;

Ellipse and ConversationBubble are classes from thewheels.users package.

_sun and _bubble are 2 INSTANCE VARIABLES

Every SunCartoon has them to keep track of, and let methods work with one Ellipse object and one ConversationBubble object.

wheels feature: Ellipse's and ConversationBubble's etc. appear graphically when they are instantiated (created via the new operator.)

public class SunCartoon extends Frame { .... public synchronized void myPause(long milliseconds)

{try {

wait(milliseconds);} catch (InterruptedException e) { }

}

I wrote method myPause Any code can call it, it's public

It makes the calling thread wait a given amount of time.Object.wait() is built-in to the Java Language.

The waiting might be interrupted..it must be in a try-catch statement for such exceptions (advanced Java concepts!)

wait() is ALSO for synchronizing this thread with another when the other calls notify()..so myPause() must be asynchronized method (advanced Java concepts!)

Life is our multi-threaded existence in the universe.

Alice project idea...animate manysimultaneously acting characters..

Java programs can be multi-threaded. this means:Multiple parts can be run as if they were started by an Alice do-together control statement.

Each “Running of a part” is called a thread.

Subtle: the thread is NOT the program code. The thread is the conceptual actor in the computer system that performs the instructions. (Advanced Java topic!)

What synchronized means in Java

Suppose one thread is running a synchronized method of an object.

Suppose a second thread calls a synchronized method of the same object.

Those methods being synchronized means the second thread will be blocked (i.e., stopped,

held up, delayed, prevented, etc.) from executing the method.

The second thread remains blocked until the first thread

exits the synchronized method, or calls wait().

Back to simple stuff..

This mutual exclusion feature prevents 2 (or more) cooks from ruining the same broth.

public class SunCartoon extends Frame { private Ellipse _sun; [ 3 ] private ConversationBubble _bubble; .... public SunCartoon() {

_sun = new Ellipse(java.awt.Color.YELLOW);[ 2 ] _bubble = new ConversationBubble("Here is Sun");

} //end of Constructor for SunCartoon's .... public static void main(String[] args) {

SunCartoon cartoon = new SunCartoon();[ 1 ] cartoon.DoAnim();

}} //end of SunCartoon class definitionThe static main method constructs one SunCartoon when theJava application starts.[ 1 ]Constructor instantiates one Ellipse & Conv.Bubble. [ 2 ]Instance variables now hold references to them for use bySunCartoon's methods. [ 3 ]

Instance variables are parts of an instance of a class.

public class SunCartoon extends Frame { private Ellipse _sun; //instance variable private ConversationBubble _bubble; //instance variable

Local variables exist only while a method is running, and they keep track of data (objects, numbers, booleans, etc) for code in the method body.

public static void main(String[] args) { SunCartoon cartoon = new SunCartoon();[ 1 ] cartoon.DoAnim();

}cartoon is a local variable belonging to the main method. It's used in the second line to refer to the SunCartoon so SunCartoon's DoAnim() method can be called.

public void DoAnim() { int nDots = 35; //a local variable. Ellipse [] array = new Ellipse[nDots]; //another local variable, for an ARRAY. //An empty array with the capacity of 35 //references to Ellipse's is constructed. for( int i = 0; i<nDots; i++) //just like complicated Alice loops. { //( here is a 3rd local variable, i, of type integer. ) array[i] = new Ellipse(java.awt.Color.GREEN); array[i].setSize(10,10); array[i].setLocation(20 + 12*i, 20 + 11*i); //35 GREEN Ellipses are one-by-one created, //drawn,made to shrink,and to move to 35 locations. myPause(200);//pause after each so it's animated. } ............ //TWO MORE loops relocate the SAME 35 Ellipses,referring to them through the LOCAL VARIABLE array.