The Artima Developer Community
Sponsored Link

Circle of Squares
A Simulation of the Java Virtual Machine

Advertisement

The Circle of Squares applet, included below, demonstrates a Java virtual machine executing a sequence of bytecodes that perform floating-point arithmetic. This applet accompanies Chapter 14, "Floating Point Arithmetic," of Inside the Java 2 Virtual Machine.

For some reason, your browser won't let you view this way cool Java applet.

The bytecode sequence in the simulation was generated by javac for the squareItForever() method of the class shown below:

// On CD-ROM in file opcodes/ex1/SquareCircle.java
class SquareCircle {

    static void squareItForever() {
        float f = 2;
        for (;;) {
            f *= f;
            f = 0 - f;
        }
    }
}

The bytecodes generated by javac for squareItForever() are shown below:

 0 fconst_2  // Push float constant 2.
 1 fstore_0  // Pop to local variable 0 (float f): float f = 2;
 2 fload_0   // Push local variable 0 (float f).
 3 fload_0   // Push local variable 0 (float f).
 4 fmul      // Pop top two floats, multiply, push float result.
 5 fstore_0  // Pop to local variable 0 (float f): f *= f;
 6 fconst_0  // Push float constant 0.
 7 fload_0   // Push local variable 0 (float f).
 8 fsub      // Subtract top float from next to top float:
             // imByte = (byte) imInt;
 9 fstore_0  // Pop result to local variable 0 (float f): f = 0 - f;
10 goto 2    // Jump back to the first fload_0 instruction:
             // for (;;) {}

The squareItForever() method repeatedly squares a float value until it hits infinity. Each time the float is squared it is also negated. The float starts out as 2. It only takes seven iterations before infinity is reached, which isn't nearly as long as it takes in real life. The hex representation of the bits that make up the float are shown in the "hex value" column in the applet. The "value" column shows the number as humans are used to seeing it. This human-friendly value is generated by the Float.toString() method.

To drive the Circle of Squares simulation, use the Step, Reset, Run, and Stop buttons. Each time you press the Step button, the simulator will execute the instruction pointed to by the pc register. If you press the Run button, the simulation will continue with no further coaxing on your part until you press the Stop button. To start the simulation over, press the Reset button. For each step of the simulation, a panel at the bottom of the applet contains an explanation of what the next instruction will do. Happy clicking.


Click here to view a page of links to the source code of the Circle of Squares applet.


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us