Version 3 of integer

Updated 2008-12-11 14:47:04 by MB

[fill in information about tcl's handling of integers - particular the new Tcl 8.5 longer integer support]

Starting from Tcl 8.5, the expr command is based on LibTomMath arbitrary precision integers :

   http://math.libtomcrypt.com/

MB Note that in Tcl releases prior to 8.5, integer calculations were performed with one of the C types long int or Tcl_WideInt. Since a "long int" is based on 32 bits, with one bit for the sign, the maximum positive integer is 2^31. The following is a little algorithm which computes the maximum integer which can be processed without truncation.

    # 
    # searchintmax --
    #   Compute the maximum integer on Tcl platform.
    #
    proc searchintmax {imax {fine 0}} {
      #
      # Search the maximum available power of 2 which keeps multiplication
      #
      set a 1
      for {set i 1} {$i<$imax} {incr i} {
        set n [expr {$a*2}]
        set p [expr {$n/2}]
        puts "a=$a, n=$n, p=$p"
        if {$p!=$a} then {
          break
        }
        set a $n
      }
      #
      # Refine process with positivity property of addition
      #
      if {$fine==1} then {
        set shift [expr {int(pow(2,30))}]
        for {set i 1} {$i<$imax} {incr i} {
          set n [expr {$a+$shift}]
          puts "a=$a, shift=$shift, n=$n"
          if {$n<=0} then {
            set shift [expr {$shift/2}]
            if {$shift==0} then {
              break
            }
          }
          set a [expr {$a + $shift}]
        }
      }
      return $a
    }

If one uses this algorithm with Tcl 8.4, one gets the 2^30=1073741824 value, which is the greatest a such (a * 2)/2 = a.

  set intmax [searchintmax 100]

With the fine=1 option, one can get the finer value 2^31=2147483647, which is the greatest a such that (a + 1) - 1 = a.

  set intmax [searchintmax 100 1]

With Tcl 8.5, the loop reaches the maximum number of iterations, which is the expected result.


See also wide.