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. Happy Easter wrote (at Sun, 26 Feb 2017, 01:47):
Easter Day Images Happy easter Images Happy easter Quotes Easter Day Images 2017 Easter Day Messages Easter Day Quotes Easter Day Pictures Easter Day Wallpapers Happy Easter Sunday Images Happy Easter Pictures Happy Easter Wallpapers Happy Easter Messages Happy Easter Pics Happy Easter Eggs Happy Easter Shayari Easter day 2017 Images Easter Day Images Quotes Happy Easter Sunday Happy easter Sunday Images Happy Easter Sunday 2017 Happy Easter Day Images

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