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)
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

Comments

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!.. https://storage.googleapis.com/ahmedchakir/mosalsal-likhtiyar-index.htm

Tue, 10 May 2022, 07:47

huay crypto: [ mail | www | link ]

Very great post I simply stumbled upon your weblog and wished to say that I have really enjoyed surfing around your weblog posts.

Thu, 05 Oct 2023, 20:33

Leave a comment

Name:  
Email: (optional)
URL: (optional)

Your comment: