Tcl 8.5: custom math functions & arbitrary precision integers

In Tcl 8.5 you can now define, at the script level (instead of needing to write in C) custom math functions. For example here is a factorial function:

proc tcl::mathfunc::fact {n} {
    if {![string is integer -strict $n] || $n < 0} then {
        return -code error "fact is only defined for non-negative integers"
    }
    set result 1
    # remember, n! (n factorial) is the product of all integers between 1 and n
    # except 0! which is defined to be 1
    for {set i 2} {$i <= $n} {incr i} {
        incr result [expr {$result * $i}]
    }
    return $result
}

Then we can use fact($n) in expr, if, while, for, etc. just like any of the "built-in" math functions.

Since we now have arbitrary precision integers (thanks Kevin!) we can compute factorials that exceed the native size of a long integer, i.e., 42!

% expr fact(42)
1405006117752879898543142606244511569936384000000000

Defining your own math functions makes solutions to Project Euler problems easier to write. YMMV. The other features of Tcl 8.5 will probably be exciting to an even wider audience.

As of January 2008 the Google calculator can only calculate up to 170!. We can do twice as better quite quickly (timings from my 2.4 GHz MacBook Pro laptop):

% time {expr {fact(171)}} 1000
295.348728 microseconds per iteration
% time {expr {fact(340)}} 1000
791.435306 microseconds per iteration

—Michael A. Cleverly

Comment:

  1. Pk Pkbooster wrote (at Tue, 10 May 2022, 07:47):

Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they%92ve added something worthwhile to the world wide web!.. https://storage.googleapis.com/ahmedchakir/mosalsal-likhtiyar-index.htm

Permanent URL for this post: http://blog.cleverly.com/permalinks/309.html