Floating-Point Arithmetic
Floating-Point Support in the Java Virtual Machine
by Bill Venners
First Published in JavaWorld, October 1996

<<  Page 3 of 3

Circle of squares: A JVM simulation
The applet below demonstrates a Java virtual machine executing a sequence of bytecodes that perform floating-point arithmetic. The bytecode sequence in the simulation was generated by javac for the squareItForever() method of the class shown below:

```     class Struggle {     static void squareItForever() {         float f = 2;         while (true) {             f = f * f;             f = 0 - f;         }     } } ```

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

``` fconst_2 // Push float constant 2. fstore_0 // Pop to local variable 0 (float f): float f = 2; fload_0 // Push local variable 0 (float f). fload_0 // Push local variable 0 (float f). fmul // Pop top two floats, multiply, push float result. fstore_0 // Pop to local variable 0 (float f): f = f * f; fconst_0 // Push float constant 0. fload_0 // Push local variable 0 (float f). fsub // Subtract top float from next to top float: imByte = (byte) imInt; fstore_0 // Pop result to local variable 0 (float f): f = 0 - f; goto 2 // Jump back to the first fload_0 instruction: while (true) {} ```

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 simulation, just press the "Step" button. Each press of the "Step" button will cause the JVM to execute one bytecode instruction. To start the simulation over, press the "Reset" button. The text area at the bottom of the applet describes the next instruction to be executed. Happy clicking.

To view the Circle of Squares applet, visit the interactive illustrations of Inside the Java Virtual Machine at:

http://www.artima.com/insidejvm/applets/CircleOfSquares.html