Java and Python multiply integers differently

From dftwiki3
Revision as of 08:28, 19 October 2015 by Thiebaut (talk | contribs) (Mult3.java)
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 );
            }
        }
}



Mulby2.cpp


Below is a C++ program afflicted with the same limitation:

// mulby2.cpp 
// D. Thiebaut
// C++ program illustrating limitation of ints,
// and possible overflow that goes undetected 
// by the program.
// 
// To compile and run:
//  g++ mulby2.cpp -o mulby2
//  ./mulby2

#include <iostream>

using namespace std;

int main() {
    //unsigned int x = 1;
    int x = 1;
    
    for ( int i=0; i<70; i++ ) {
        cout <<  x << endl;
        // cout << x << endl;
        x = x * 2;
    }
    
    cout << x << endl << endl;
    return 0;
}