Java and Python multiply integers differently

From dftwiki3
Revision as of 09:21, 19 October 2015 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- =Mult2.java= <br /> Below is a program in Java that accumulates ints in a variable, making the contents grow larger, until something unfortunate happens... <br /> ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 09:21, 19 October 2015 (EDT)


Mult2.java


Below is a program in Java that accumulates ints in a variable, making the contents grow larger, until something unfortunate happens...

/*
  Mult2.java
  keep accumulating some number in an integer, and
  see what happens when it gets to some large value...

  To compile and run:

  javac Mult2.java
  java Mult2
 */

class Mult2 {
    public static void main( String[] args ) {

        int a = 1;
        System.out.println( "a = " + a );

        for ( int i=0; i<70; i++ ) {
            a = a*2;
            System.out.println( "a = " + a );
        }

    }
}


Exercise
Change the int (32 bits) to a long (64 bits). How does the output change? Still the same problem?


Mult2.py


Below is the same program in Python:

# Mult2.py
# Demonstrate how Python reacts to integers that
# increase in size.

a = 1

for i in range( 70 ):
    a = a*2
    print( "a = ", a )


Mult3.java


Below is a program showing how to avoid the "bug" resulting from an integer overflow.

# Mult3.java
# D. Thiebaut
# Example of overflow in an int, and how to use the BigInteger library.

public class Mult3 {

        public static void main(String[] args) {
            int x = 1;
            BigInteger xx = BigInteger.valueOf( x );
            BigInteger big2 = BigInteger.valueOf( 2 );

            for (int i=0; i<70; i++ ) {
                // -----------------------------------------------
                // a multiplication of ints
                x = x * 2;

                System.out.println( "x  = " + x  );
                
                // -----------------------------------------------
                // a multiplication of BigIntegers
                xx = xx.multiply( big2 );

                System.out.println( "xx = " + xx );
            }
        }
}