|
ActiveTcl User Guide |
|
[ Main table Of Contents | Tcllib Table Of Contents | Tcllib Index ]
math::bigfloat(n) 2.0 "Tcl Math Library"
math::bigfloat - Arbitrary precision floating-point numbers
TABLE OF
CONTENTS
SYNOPSIS
DESCRIPTION
INTRODUCTION
ARITHMETICS
COMPARISONS
ANALYSIS
ROUNDING
PRECISION
WHAT ABOUT
TCL 8.4 ?
NAMESPACES AND OTHER
PACKAGES
EXAMPLES
KEYWORDS
COPYRIGHT
package require Tcl 8.5
package require math::bigfloat ?2.0?
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 :
- BigFloat for floating-point numbers of arbitrary length.
- integers for arbitrary length signed integers, just as basic
integers since Tcl 8.5.
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. BigFloats
are internally represented at Tcl lists: this package provides a
set of procedures operating against the internal representation in
order to :
- perform math operations on BigFloats and (optionnaly) with
integers.
- convert BigFloats from their internal representations to
strings, and vice versa.
- fromstr number ?trailingZeros?
- Converts number into a BigFloat. Its precision is at
least the number of digits provided by number. If the number contains only digits and eventually a minus
sign, it is considered as an integer. Subsequently, no conversion
is done at all.
trailingZeros - the number of zeros to append at
the end of the floating-point number to get more precision. It
cannot be applied to an integer.
| |
# x and y are BigFloats : the first string contained a dot, and the second an e sign
set x [fromstr -1.000000]
set y [fromstr 2000e30]
# let's see how we get integers
set t 20000000000000
# the old way (package 1.2) is still supported for backwards compatibility :
set m [fromstr 10000000000]
# but we do not need fromstr for integers anymore
set n -39
# t, m and n are integers
|
The number's last digit is considered by the procedure to
be true at +/-1, For example, 1.00 is the interval [0.99, 1.01],
and 0.43 the interval [0.42, 0.44]. The Pi constant may be
approximated by the number "3.1415". This string could be
considered as the interval [3.1414 , 3.1416] by fromstr. So, when you mean 1.0 as a double, you may have
to write 1.000000 to get enough precision. To learn more about this
subject, see PRECISION.
For example :
| |
set x [fromstr 1.0000000000]
# the next line does the same, but smarter
set y [fromstr 1. 10]
|
- tostr number
- Returns a string form of a BigFloat, in which all digits are
exacts. number may be an integer, causing the command to
return exactly the input argument.
| |
# the following prints '1.0000' because the last '1' is uncertain
puts [tostr [fromstr 1.00001]]
|
There is an issue with number equal to zero (see PRECISION) : even if the precision about 0 is more
than one digit, it will always be displayed as the '0'
string. A number belonging to an interval in which 0 is contained
behaves always like that. This example show numbers that are
considered as '0':
| |
fromstr 0.1 ; # interval [0, 0.2]
fromstr 0.000001 ; # interval [0, 0.000002]
fromstr -0.000001 ; # interval [-0.000002, 0]
fromstr 0.0 ; # interval [-0.1, 0.1]
fromstr 0. 10; # interval [-1.e-10, 1.e-10]
|
- fromdouble double ?decimals?
- Converts a double (a simple floating-point value) to a
BigFloat, with exactly decimals digits. Without
the decimals argument, it behaves like
fromstr.
| |
tostr [fromstr 1.111 4]
# returns : 1.111000 (3 zeros)
tostr [fromdouble 1.111 4]
# returns : 1.111
|
- todouble number
- Returns a double, that may be used in expr, from a
BigFloat.
- isInt number
- Returns 1 if number is an integer, 0 otherwise.
- isFloat number
- Returns 1 if number is a BigFloat, 0 otherwise.
- int2float integer ?decimals?
- Converts an integer to a BigFloat with decimals
trailing zeros. The default, and minimal, number of
decimals is 1. When converting back to string, one decimal
is lost:
| |
set n 10
set x [int2float $n]; # like fromstr 10.0
puts [tostr $x]; # prints "10."
set x [int2float $n 3]; # like fromstr 10.000
puts [tostr $x]; # prints "10.00"
|
- add x y
- sub x y
- mul x y
- Return the sum, difference and product of x by
y. x - may be either a BigFloat or an
integer y - may be either a BigFloat or an
integer When both are integers, these commands behave like expr.
- div x y
- mod x y
- Return the quotient and the rest of x divided by
y. Each argument (x and y) can be either
a BigFloat or an integer, but you cannot divide an integer by a
BigFloat Divide by zero throws an error.
- abs x
- Returns the absolute value of x
- opp x
- Returns the opposite of x
- pow x n
- Returns x taken to the nth power. It only
works if n is an integer. x might be a BigFloat
or an integer.
- iszero x
- Returns 1 if x is :
- a BigFloat close enough to zero to raise "divide by zero".
- the integer 0.
- equal x y
- Returns 1 if x and y are equal, 0
elsewhere.
- compare x y
- Returns 0 if both BigFloat arguments are equal, 1 if x
is greater than y, and -1 if x is lower than
y. You would not be able to compare an integer to a
BigFloat : the operands should be both BigFloats, or both
integers.
- 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
- The above functions return, respectively, the following :
square root, logarithm, exponential, cosine, sine, tangent,
cotangent, arc cosine, arc sine, arc tangent, hyperbolic cosine,
hyperbolic sine, hyperbolic tangent, of a BigFloat named
x.
- pi n
- Returns a BigFloat representing the Pi constant with n
digits after the dot. n is a positive integer.
- rad2deg radians
- deg2rad degrees
- radians - angle expressed in radians
(BigFloat)
degrees - angle expressed in degrees
(BigFloat)
Convert an angle from radians to degrees, and vice
versa.
- round x
- ceil x
- floor x
- The above functions return the x BigFloat, rounded
like with the same mathematical function in expr, and
returns it as an integer.
How do conversions work with precision ?
- When a BigFloat is converted from string, the internal
representation holds its uncertainty as 1 at the level of the last
digit.
- During computations, the uncertainty of each result is
internally computed the closest to the reality, thus saving the
memory used.
- When converting back to string, the digits that are printed are
not subject to uncertainty. However, some rounding is done, as not
doing so causes severe problems.
Uncertainties are kept in the internal representation of the number
; it is likely 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.
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 you are put into uncertainty:
| |
set a [fromstr 1.230]
# $a is internally contained in the interval [1.230 - d*10^-3, 1.230 + d*10^-3]
# with d as close as possible to 1,
# so $a belongs to [1.229, 1.231] in practice
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 the uncertainty of each number.
| |
set a [fromstr 1.230]
set b [fromstr 2.340]
puts [tostr [add $a $b]]
# the result is : 3.57 and the last digit of the sum is known with an uncertainty of 2*10^-3
|
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
# b has only 3 digits
set b [fromstr 2.00]
# the result has less than 3 digits
mul $a $b
# if we are clever, we would keep the same precision in the result as in $a
puts [tostr [mul $a 2]]
# that's it!
|
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 about the fact that if a number contains 0 in its
uncertainty interval, it is always considered as if it was 0.
| |
set num [fromstr 4.00]
set denom [fromstr 0.01]
puts [tostr $denom];# prints "0" on the screen
set quotient [div $num $denom];# throws an error : divide by zero
# computing opposites of $num and $denom
set oppn [opp $num]
set oppd [opp $denom]
puts [compare $num $oppn];#prints 1 as $num>0 and $oppn<0
puts [compare $denom $oppd];#prints 0 ! Suprise?
# No! 0 compared to (-)0 gives an equality...
#
# 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
# please note, in the following, that leading zeros do not matter!
puts [tostr [cos [fromstr 0e-10]]]; # -> 1.000000000
puts [tostr [cos [fromstr 1e-10]]]; # -> 1.000000000
|
Although BigFloats may be printed as "0", each of their internal
representations may be different. Of course, this is also true for
any BigFloat : you can see it by looking at their values like in
this short example:
| |
puts [fromstr 0.0001]
puts [fromstr 0.00010]
|
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]]"
|
computations , floating-point , interval , math , multiprecision , tcl
Copyright © 2004-2005, by Stephane Arnold
<stephanearnold at yahoo dot fr>