Tcl Library Source Code

EuroTcl/OpenACS 11 - 12 JULY 2024, VIENNA

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


math::bigfloat - Arbitrary precision floating-point numbers

Table Of Contents


package require Tcl 8.5 9
package require math::bigfloat ?2.0.5?

fromstr number ?trailingZeros?
tostr ?-nosci? number
fromdouble double ?decimals?
todouble number
isInt number
isFloat number
int2float integer ?decimals?
add x y
sub x y
mul x y
div x y
mod x y
abs x
opp x
pow x n
iszero x
equal x y
compare x y
sqrt x
log x
exp x
cos x
sin x
tan x
cotan x
acos x
asin x
atan x
cosh x
sinh x
tanh x
pi n
rad2deg radians
deg2rad degrees
round x
ceil x
floor x


The bigfloat package provides arbitrary precision floating-point math capabilities to the Tcl language. It is designed to work with Tcl 8.5, but for Tcl 8.4 is provided an earlier version of this package. See WHAT ABOUT TCL 8.4 ? for more explanations. By convention, we will talk about the numbers treated in this library as :

Each BigFloat is an interval, namely [m-d, m+d], where m is the mantissa and d the uncertainty, representing the limitation of that number's precision. This is why we call such mathematics interval computations. Just take an example in physics : when you measure a temperature, not all digits you read are significant. Sometimes you just cannot trust all digits - not to mention if doubles (f.p. numbers) can handle all these digits. BigFloat can handle this problem - trusting the digits you get - plus the ability to store numbers with an arbitrary precision. BigFloats are internally represented at Tcl lists: this package provides a set of procedures operating against the internal representation in order to :







How do conversions work with precision ?

Uncertainties are kept in the internal representation of the number ; it is recommended to use tostr only for outputting data (on the screen or in a file), and NEVER call fromstr with the result of tostr. It is better to always keep operands in their internal representation. Due to the internals of this library, the uncertainty interval may be slightly wider than expected, but this should not cause false digits.

Now you may ask this question : What precision am I going to get after calling add, sub, mul or div? First you set a number from the string representation and, by the way, its uncertainty is set:

set a [fromstr 1.230]
# $a belongs to [1.229, 1.231]
set a [fromstr 1.000]
# $a belongs to [0.999, 1.001]
# $a has a relative uncertainty of 0.1% : 0.001(the uncertainty)/1.000(the medium value)

The uncertainty of the sum, or the difference, of two numbers, is the sum of their respective uncertainties.

set a [fromstr 1.230]
set b [fromstr 2.340]
set sum [add $a $b]]
# the result is : [3.568, 3.572] (the last digit is known with an uncertainty of 2)
tostr $sum ; # 3.57

But when, for example, we add or substract an integer to a BigFloat, the relative uncertainty of the result is unchanged. So it is desirable not to convert integers to BigFloats:

set a [fromstr 0.999999999]
# now something dangerous
set b [fromstr 2.000]
# the result has only 3 digits
tostr [add $a $b]

# how to keep precision at its maximum
puts [tostr [add $a 2]]

For multiplication and division, the relative uncertainties of the product or the quotient, is the sum of the relative uncertainties of the operands. Take care of division by zero : check each divider with iszero.

set num [fromstr 4.00]
set denom [fromstr 0.01]

puts [iszero $denom];# true
set quotient [div $num $denom];# error : divide by zero

# opposites of our operands
puts [compare $num [opp $num]]; # 1
puts [compare $denom [opp $denom]]; # 0 !!!
# No suprise ! 0 and its opposite are the same...

Effects of the precision of a number considered equal to zero to the cos function:

puts [tostr [cos [fromstr 0. 10]]]; # -> 1.000000000
puts [tostr [cos [fromstr 0. 5]]]; # -> 1.0000
puts [tostr [cos [fromstr 0e-10]]]; # -> 1.000000000
puts [tostr [cos [fromstr 1e-10]]]; # -> 1.000000000

BigFloats with different internal representations may be converted to the same string.

For most analysis functions (cosine, square root, logarithm, etc.), determining the precision of the result is difficult. It seems however that in many cases, the loss of precision in the result is of one or two digits. There are some exceptions : for example,

tostr [exp [fromstr 100.0 10]]
# returns : 2.688117142e+43 which has only 10 digits of precision, although the entry
# has 14 digits of precision.


If your setup do not provide Tcl 8.5 but supports 8.4, the package can still be loaded, switching back to math::bigfloat 1.2. Indeed, an important function introduced in Tcl 8.5 is required - the ability to handle bignums, that we can do with expr. Before 8.5, this ability was provided by several packages, including the pure-Tcl math::bignum package provided by tcllib. In this case, all you need to know, is that arguments to the commands explained here, are expected to be in their internal representation. So even with integers, you will need to call fromstr and tostr in order to convert them between string and internal representations.

# with Tcl 8.5
# ============
set a [pi 20]
# round returns an integer and 'everything is a string' applies to integers
# whatever big they are
puts [round [mul $a 10000000000]]
# the same with Tcl 8.4
# =====================
set a [pi 20]
# bignums (arbitrary length integers) need a conversion hook
set b [fromstr 10000000000]
# round returns a bignum:
# before printing it, we need to convert it with 'tostr'
puts [tostr [round [mul $a $b]]]


We have not yet discussed about namespaces because we assumed that you had imported public commands into the global namespace, like this:

namespace import ::math::bigfloat::*

If you matter much about avoiding names conflicts, I considere it should be resolved by the following :

package require math::bigfloat
# beware: namespace ensembles are not available in Tcl 8.4
namespace eval ::math::bigfloat {namespace ensemble create -command ::bigfloat}
# from now, the bigfloat command takes as subcommands all original math::bigfloat::* commands
set a [bigfloat sub [bigfloat fromstr 2.000] [bigfloat fromstr 0.530]]
puts [bigfloat tostr $a]


Guess what happens when you are doing some astronomy. Here is an example :

# convert acurrate angles with a millisecond-rated accuracy
proc degree-angle {degrees minutes seconds milliseconds} {
    set result 0
    set div 1
    foreach factor {1 1000 60 60} var [list $milliseconds $seconds $minutes $degrees] {
        # we convert each entry var into milliseconds
        set div [expr {$div*$factor}]
        incr result [expr {$var*$div}]
    return [div [int2float $result] $div]
# load the package
package require math::bigfloat
namespace import ::math::bigfloat::*
# work with angles : a standard formula for navigation (taking bearings)
set angle1 [deg2rad [degree-angle 20 30 40   0]]
set angle2 [deg2rad [degree-angle 21  0 50 500]]
set opposite3 [deg2rad [degree-angle 51  0 50 500]]
set sinProduct [mul [sin $angle1] [sin $angle2]]
set cosProduct [mul [cos $angle1] [cos $angle2]]
set angle3 [asin [add [mul $sinProduct [cos $opposite3]] $cosProduct]]
puts "angle3 : [tostr [rad2deg $angle3]]"

Bugs, Ideas, Feedback

This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category math :: bignum :: float of the Tcllib Trackers. Please also report any ideas for enhancements you may have for either package and/or documentation.

When proposing code changes, please provide unified diffs, i.e the output of diff -u.

Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar.


computations, floating-point, interval, math, multiprecision, tcl




Copyright © 2004-2008, by Stephane Arnold