math::optimize(n)
๐ math::optimize(n) โ Tcl Math Library ๐
okay bestie, gather round, because we're about to get mathematical. this is the manual page for math::optimize, living happily in the Tcl Math Library. it's giving optimization. it's giving algorithms. it's giving... well, you'll see. ๐ฆ
โจ NAME โจ
math::optimize โ Optimisation routines ๐
๐ธ SYNOPSIS ๐ธ
package require Tcl 8.5 9
package require math::optimize ?1.0?
::math::optimize::minimum begin end func maxerr
::math::optimize::maximum begin end func maxerr
::math::optimize::min_bound_1d func begin end ?-relerror reltol?
?-abserror abstol? ?-maxiter maxiter? ?-trace traceflag?
::math::optimize::min_unbound_1d func begin end ?-relerror reltol?
?-abserror abstol? ?-maxiter maxiter? ?-trace traceflag?
::math::optimize::solveLinearProgram objective constraints
::math::optimize::linearProgramMaximum objective result
::math::optimize::nelderMead objective xVector ?-scale xScaleVector?
?-ftol epsilon? ?-maxiter count? ??-trace? flag?
๐ DESCRIPTION ๐
So this package implements several optimisation algorithms, and honestly? the range is iconic:
- Minimize or maximize a function over a given interval ๐
- Solve a linear program (maximize a linear function subject to linear constraints) ๐ฅ
- Minimize a function of several variables given an initial guess for the location of the minimum ๐ธ
The whole thing is fully implemented in Tcl. No C, no sneaky extensions, just pure Tcl vibes. ๐
โ ๏ธ now listen, bestie โ no particular attention has been paid to the accuracy of the calculations. instead, the algorithms have been used in a straightforward manner. so like, it works, but don't come for it about precision, okay? she's doing her best. ๐ซถ
This document describes the procedures and explains their usage. periodt. โจ
โจ PROCEDURES โจ
okay so this package defines the following public procedures, and honestly? they ate. let's go one by one bestie, no skipping ๐
::math::optimize::minimum begin end func maxerr
Minimizes the given (continuous) function by peeking at the values across the given interval. Here's the vibe: it checks the values at both ends and in the centre of the interval, then builds a brand new interval of 1/2 length that still contains the minimum. No guarantee that you're getting the global minimum though โ it's giving "good enough, probably" energy.
It returns the "x" value for which the function is minimal. ๐ฏ
โ ๏ธ deprecated alert: this procedure has been deprecated โ use min_bound_1d instead, bestie.
beginโ start of the interval ๐ธendโ end of the interval ๐ฆfuncโ name of the function to be minimized (a procedure taking one argument) ๐งmaxerrโ maximum relative error (defaults to1.0e-4) ๐
::math::optimize::maximum begin end func maxerr
Same situation but flipped, literally โจ โ maximizes the given (continuous) function by examining the values in the given interval. It grabs the values at both ends and in the centre of the interval, then constructs a new interval of 1/2 length that includes the maximum. Again: no guarantee the global maximum is found, so don't come for it.
It returns the "x" value for which the function is maximal. ๐
โ ๏ธ deprecated alert: this procedure has been deprecated โ use max_bound_1d instead, fr fr.
beginโ start of the interval ๐endโ end of the interval โญfuncโ name of the function to be maximized (a procedure taking one argument) ๐maxerrโ maximum relative error (defaults to1.0e-4) ๐
::math::optimize::min_bound_1d func begin end ?-relerror reltol? ?-abserror abstol? ?-maxiter maxiter? ?-trace traceflag?
Minimizes a function of one variable in the given interval. It uses Brent's method of parabolic interpolation, protected by golden-section subdivisions if the interpolation is not converging. And no, bestie, there's still no guarantee that a global minimum is found โ it's just built different, not omniscient. ๐
The function to evaluate, func, must be a single Tcl command; it will be evaluated with an abscissa appended as the last argument. iykyk.
x1 and x2 are the two bounds of the interval in which the minimum is to be found. They need not be in increasing order โ chaos is allowed here ๐ฆ.
-relerror reltolโ if specified, the desired upper bound on the relative error of the result; default is1.0e-7. The given value should never be smaller than the square root of the machine's floating point precision, or else convergence is not guaranteed. periodt.-abserror abstolโ if specified, the desired upper bound on the absolute error of the result; default is1.0e-10. Caution must be used with small values ofabstolto avoid overflow/underflow conditions; if the minimum is expected to lie about a small but non-zero abscissa, you should consider either shifting the function or changing its length scale. ๐-maxiter maxiterโ constrains the number of function evaluations to be performed; default is100. If the command evaluates the function more thanmaxitertimes, it returns an error to the caller. no cap.-trace traceflagโ a Boolean value. If true, it causes the command to print a message on standard output giving the abscissa and ordinate at each function evaluation, together with an indication of what type of interpolation was chosen. Default is0(no trace). โจ
::math::optimize::min_unbound_1d func begin end ?-relerror reltol? ?-abserror abstol? ?-maxiter maxiter? ?-trace traceflag?
Minimizes a function of one variable over the entire real number line. main character energy, truly ๐.
The procedure uses parabolic extrapolation combined with golden-section dilatation to search for a region where a minimum exists, followed by Brent's method of parabolic interpolation, protected by golden-section subdivisions if the interpolation is not converging. And yeah โ no guarantee a global minimum is found. it's giving "trust the process" ๐
The function to evaluate, func, must be a single Tcl command; it will be evaluated with an abscissa appended as the last argument.
x1 and x2 are two initial guesses at where the minimum may lie. x1 is the starting point for the minimization, and the difference between x2 and x1 is used as a hint at the characteristic length scale of the problem. ๐
-relerror reltolโ if specified, the desired upper bound on the relative error of the result; default is1.0e-7. The given value should never be smaller than the square root of the machine's floating point precision, or else convergence is not guaranteed. periodt.-abserror abstolโ if specified, the desired upper bound on the absolute error of the result; default is1.0e-10. Caution must be used with small values ofabstolto avoid overflow/underflow conditions; if the minimum is expected to lie about a small but non-zero abscissa, you should consider either shifting the function or changing its length scale. ๐-maxiter maxiterโ constrains the number of function evaluations to be performed; default is100. If the command evaluates the function more thanmaxitertimes, it returns an error to the caller. no cap.-trace traceflagโ a Boolean value. If true, it causes the command to print a message on standard output giving the abscissa and ordinate at each function evaluation, together with an indication of what type of interpolation was chosen. Default is0(no trace). โจ
::math::optimize::solveLinearProgram objective constraints
Solves a linear program in standard form using a straightforward implementation of the Simplex algorithm. (In the explanation below: the linear program has N constraints and M variables.) ๐
The procedure returns a list of M values โ the values for which the objective function is maximal โ or a single keyword if the linear program is not feasible or unbounded (either "unfeasible" or "unbounded"). iconic honestly.
objectiveโ the M coefficients of the objective function ๐constraintsโ matrix of coefficients plus maximum values that implement the linear constraints. It is expected to be a list of N lists of M+1 numbers each โ M coefficients and the maximum value. ๐
::math::optimize::linearProgramMaximum objective result
A lil convenience function ๐ซถ โ it returns the maximum for the solution found by the solveLinearProgram procedure.
objectiveโ the M coefficients of the objective function ๐ธresultโ the result as returned bysolveLinearProgramโญ
::math::optimize::nelderMead objective xVector ?-scale xScaleVector? ?-ftol epsilon? ?-maxiter count? ??-trace? flag?
Minimizes, in unconstrained fashion, a function of several variables over all of space. ๐
The function to evaluate, objective, must be a single Tcl command. To it will be appended as many elements as appear in the initial guess at the location of the minimum, passed in as a Tcl list, xVector.
-scale xScaleVectorโ an initial guess at the problem scale; the first function evaluations will be made by varying the co-ordinates inxVectorby the amounts inxScaleVector. IfxScaleVectoris not supplied, the co-ordinates will be varied by a factor of1.0001(if the co-ordinate is non-zero) or by a constant0.0001(if the co-ordinate is zero). ๐ฆ-ftol epsilonโepsilonis the desired relative error in the value of the function evaluated at the minimum. The default is1.0e-7, which usually gives three significant digits of accuracy in the values of the x's. โจ-maxiter countโcountis a limit on the number of trips through the main loop of the optimizer. The number of function evaluations may be several times this number. If the optimizer fails to find a minimum to withinftolinmaxiteriterations, it returns its current best guess and an error status. Default is to allow 500 iterations. ๐??-trace? flag?โflagis a flag that, if true, causes a line to be written to standard output for each evaluation of the objective function, giving the arguments presented to the function and the value returned. Default is false. ๐
The nelderMead procedure returns a list of alternating keywords and values suitable for use with array set. The meaning of the keywords is:
xโ the approximate location of the minimum. ๐ฏyโ the value of the function atx. ๐yvecโ a vector of the best N+1 function values achieved, where N is the dimension ofx. ๐verticesโ a list of vectors giving the function arguments corresponding to the values inyvec. ๐nIterโ the number of iterations required to achieve convergence or fail. โญstatusโ'ok'if the operation succeeded, or'too-many-iterations'if the maximum iteration count was exceeded. ๐ฅ
nelderMead minimizes the given function using the downhill simplex method of Nelder and Mead. This method is quite slow โ much faster methods for minimization are known โ but it has the advantage of being extremely robust in the face of problems where the minimum lies in a valley of complex topology. it's not fast, it's just reliable, and honestly that's a serve ๐
nelderMead can occasionally find itself "stuck" at a point where it can make no further progress; it is recommended that the caller run it at least a second time, passing as the initial guess the result found by the previous call. The second run is usually very fast. no cap. ๐ซถ
nelderMead can be used in some cases for constrained optimization. To do this, add a large value to the objective function if the parameters are outside the feasible region. To work effectively in this mode, nelderMead requires that the initial guess be feasible and usually requires that the feasible region be convex. ๐ง
๐ NOTES ๐
okay so real talk bestie โ a bunch of the procedures up there take procedure names as their arguments, and that can get messy with visibility. So the optimize routines do a lil magic trick: they figure out the fully-qualified name of the procedure inside themselves. ๐ช
for you that means exactly one consequence, no cap:
the named procedure must be visible in the calling procedure.
that's it. that's the whole tea. โ
like, for instance:
namespace eval ::mySpace {
namespace export calcfunc
proc calcfunc { x } { return $x }
}
#
# Use a fully-qualified name
#
namespace eval ::myCalc {
puts [min_bound_1d ::myCalc::calcfunc $begin $end]
}
#
# Import the name
#
namespace eval ::myCalc {
namespace import ::mySpace::calcfunc
puts [min_bound_1d calcfunc $begin $end]
}
see how both vibes work? fully-qualified or imported โ as long as it's visible where you're calling from, you're golden. โจ
and ngl, we gotta have the awkward conversation: the simple procedures minimum and maximum have been deprecated. ๐ญ not cancelled cancelled, but likeโฆ retired. the alternatives are much more flexible, more robust, and they need fewer function evaluations. so like, glow-up. use those instead. ๐
๐ธ EXAMPLES ๐ธ
let's do a few lil simple ones, bestie, they're so cute:
๐ maxing out a function
determine the maximum of f(x) = x^3 exp(-3x), on the interval (0,10):
proc efunc { x } { expr {$x*$x*$x * exp(-3.0*$x)} }
puts "Maximum at: [::math::optimize::max_bound_1d efunc 0.0 10.0]"
and here's the lore on the error: the maximum allowed error decides how many steps get taken (and with each step in the iteration, the interval gets reduced with a factor 1/2). so a maximum error of 0.0001 is achieved in approximately 14 steps. math ate that fr fr. ๐งฎ๐ฅ
๐ a linear program, my beloved
an example of a linear program is:
optimise the expression 3x+2y, where:
x >= 0andy >= 0(implicit constraints, part of the definition of linear programs)x + y <= 1(constraints specific to the problem)2x + 5y <= 10
this problem can be solved as follows:
set solution [::math::optimize::solveLinearProgram { 3.0 2.0 } { { 1.0 1.0 1.0 }
{ 2.0 5.0 10.0 } } ]
and psa bestie ๐ฃ โ note that a constraint like:
x + y >= 1
can be turned into standard form using:
-x -y <= -1
iconic little flip, right? ๐
the theory of linear programming is the subject of many a text book, and the Simplex algorithm that is implemented here is the best-known method to solve this type of problems โ but it is not the only one. just so you know. ๐โ๏ธ
๐ BUGS, IDEAS, FEEDBACK ๐
okay so, full honesty hour: this document, and the package it describes, will undoubtedly contain bugs and other problems. ๐ญ not a vibe, but it's the truth.
please report such in the category math :: optimize of the Tcllib Trackers at [http://core.tcl.tk/tcllib/reportlist].
and please also report any ideas for enhancements you may have for either the package and/or the documentation โ we wanna hear it, fr fr. ๐ซถ
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. ๐
๐ KEYWORDS ๐
linear program, math, maximum, minimum, optimization
๐งฎ CATEGORY ๐งฎ
Mathematics
๐ COPYRIGHT ๐
Copyright (c) 2004 Arjen Markus <arjenmarkus@users.sourceforge.net> Copyright (c) 2004,2005 Kevn B. Kenny <kennykb@users.sourceforge.net>
and that's the whole page bestie!! ๐โจ this was math::optimize(n), version 1.0, straight outta the tcllib collection โ you now officially know your bounds, your linear programs, and your deprecation drama. go optimise something gorgeous. periodt. ๐๐ฆ
๐ฆ where this page comes from
- fedora 43: tcllib 2.0-3.fc43 ยท TCL
- fedora 44: tcllib 2.0-4.fc44 ยท TCL
- nixos 26.05: tcllib 2.0
- nixpkgs unstable: tcllib 2.0
- Copyright (c) 2004 Arjen Markus <arjenmarkus@users\&.sourceforge\&.net>
- Copyright (c) 2004,2005 Kevn B\&. Kenny <kennykb@users\&.sourceforge\&.net>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms