Tcl 8.5: custom math functions & arbitrary precision integers

(Printer friendly version)

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)

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


Pk Pkbooster: [ mail | www | link ]

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!..

Tue, 10 May 2022, 07:47

pgslot login: [ mail | www | link ]
This is very interesting, You%92re a very skilled blogger. I%92ve joined your rss feed and look forward to seeking more of your great post. Also, I%92ve shared your web site in my social networks! pgslot login

Sun, 29 Jan 2023, 04:55

Leave a comment

Email: (optional)
URL: (optional)

Your comment: