Tcl Library Source Code

Documentation
Login


[ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]

NAME

math::exact - Exact Real Arithmetic

Table Of Contents

SYNOPSIS

package require Tcl 8.6
package require grammar::aycock 1.0
package require math::exact 1.0.1

::math::exact::exactexpr expr
number ref
number unref
number asPrint precision
number asFloat precision

DESCRIPTION

The exactexpr command in the math::exact package allows for exact computations over the computable real numbers. These are not arbitrary-precision calculations; rather they are exact, with numbers represented by algorithms that produce successive approximations. At the end of a calculation, the caller can request a given precision for the end result, and intermediate results are computed to whatever precision is necessary to satisfy the request.

Procedures

The following procedure is the primary entry into the math::exact package.

Parameters

Expressions

The math::exact::exactexpr command accepts expressions in a subset of Tcl's syntax. The following components may be used in an expression.

Functions

The following functions are available for use within exact real expressions.

Summary

The math::exact::exactexpr command provides a system that performs exact arithmetic over computable real numbers, representing the numbers as algorithms for successive approximation. An example, which implements the high-school quadratic formula, is shown below.

namespace import math::exact::exactexpr
proc exactquad {a b c} {
    set d [[exactexpr {sqrt($b*$b - 4*$a*$c)}] ref]
    set r0 [[exactexpr {(-$b - $d) / (2 * $a)}] ref]
    set r1 [[exactexpr {(-$b + $d) / (2 * $a)}] ref]
    $d unref
    return [list $r0 $r1]
}

set a [[exactexpr 1] ref]
set b [[exactexpr 200] ref]
set c [[exactexpr {(-3/2) * 10**-12}] ref]
lassign [exactquad $a $b $c] r0 r1
$a unref; $b unref; $c unref
puts [list [$r0 asFloat 70] [$r1 asFloat 110]]
$r0 unref; $r1 unref

The program prints the result:

-2.000000000000000075e2 7.499999999999999719e-15

Note that if IEEE-754 floating point had been used, a catastrophic roundoff error would yield a smaller root that is a factor of two too high:

-200.0 1.4210854715202004e-14

The invocations of exactexpr should be fairly self-explanatory. The other commands of note are ref and unref. It is necessary for the caller to keep track of references to exact expressions - to call ref every time an exact expression is stored in a variable and unref every time the variable goes out of scope or is overwritten. The asFloat method emits decimal digits as long as the requested precision supports them. It terminates when the requested precision yields an uncertainty of more than one unit in the least significant digit.

CATEGORY

Mathematics

COPYRIGHT

Copyright © 2015 Kevin B. Kenny Redistribution permitted under the terms of the Open Publication License http://www\.opencontent\.org/openpub/