# FreeBSD Manual Pages

mpexpr(TCL) mpexpr(TCL)NAMEmpexpr - Evaluate an expression with multiple precision mathSYNOPSISpackagerequireMpexprmpexprarg?argarg...?mpformatformatString?argarg...?globalmp_precisionDESCRIPTIONMpexpr is based on Tcl's nativeexprcommand, and shares many similari- ties withexpr. Mpexpr performs all of its calculations using an arbi- trary precision math package. Mpexpr concatenatesarg's (adding separator spaces between them), eval- uates the result as a Tcl expression, and returns the value. The oper- ators permitted in Tcl expressions are a subset of the operators per- mitted in C expressions, and they have the same meaning and precedence as the corresponding C operators. Expressions almost always yield nu- meric results (integer or floating-point values). For example, the ex- pressionmpexpr8.2+6evaluates to 14.2. Tcl expressions differ from C expressions in the way that operands are specified. Also, Tcl expressions support non-nu- meric operands and string comparisons.OPERANDSA Tcl expression consists of a combination of operands, operators, and parentheses. White space may be used between the operands and opera- tors and parentheses; it is ignored by the expression processor. Where possible, operands are interpreted as integer values. Integer values may be specified in decimal (the normal case), in octal (if the first character of the operand is0), or in hexadecimal (if the first two characters of the operand are0x). If an operand does not have one of the integer formats given above, then it is treated as a floating-point number if that is possible. Floating-point numbers may be specified in any of the ways accepted by an ANSI-compliant C compiler (except that the ``f'', ``F'', ``l'', and ``L'' suffixes will not be permitted in most installations). For example, all of the following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. If no numeric inter- pretation is possible, then an operand is left as a string (and only a limited set of operators may be applied to it). Operands may be specified in any of the following ways: [1] As an numeric value, either integer or floating-point. [2] As a Tcl variable, using standard$notation. The variable's value will be used as the operand. [3] As a string enclosed in double-quotes. The expression parser will perform backslash, variable, and command substitutions on the information between the quotes, and use the resulting value as the operand [4] As a string enclosed in braces. The characters between the open brace and matching close brace will be used as the operand with- out any substitutions. [5] As a Tcl command enclosed in brackets. The command will be exe- cuted and its result will be used as the operand. [6] As a mathematical function whose arguments have any of the above forms for operands, such as ``sin($x)''. See below for a list of defined functions. Where substitutions occur above (e.g. inside quoted strings), they are performed by the expression processor. However, an additional layer of substitution may already have been performed by the command parser be- fore the expression processor was called. As discussed below, it is usually best to enclose expressions in braces to prevent the command parser from performing substitutions on the contents. For some examples of simple expressions, suppose the variableahas the value 3 and the variablebhas the value 6. Then the command on the left side of each of the lines below will produce the value on the fol- lowing line:mpexpr3.1+$a6.1mpexpr2+"$a.$b"5.6mpexpr4*[llength"62"]8mpexpr{{wordone}<"word$a"}0OPERATORSThe valid operators are listed below, grouped in decreasing order of precedence:-+~!Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operands may be applied to string op- erands, and bit-wise NOT may be applied only to in- tegers.*/%Multiply, divide, remainder. None of these oper- ands may be applied to string operands, and remain- der may be applied only to integers. The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor.+-Add and subtract. Valid for any numeric operands. << >> Left and right shift. Valid for integer operands only. Integers in mpexpr are not limited to a ma- chine word and do not use two's complement format. Therefore shifting will not include a sign bit. < > <=>=Boolean less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These opera- tors may be applied to strings as well as numeric operands, in which case string comparison is used.==!=Boolean equal and not equal. Each operator pro- duces a zero/one result. Valid for all operand types. & Bit-wise AND. Valid for integer operands only.^Bit-wise exclusive OR. Valid for integer operands only.|Bit-wise OR. Valid for integer operands only. && Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for numeric oper- ands only (integers or floating-point).||Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for numeric operands only (integers or floating-point).x?y:zIf-then-else, as in C. Ifxevaluates to non-zero, then the result is the value ofy. Otherwise the result is the value ofz. Thexoperand must have a numeric value. See the C manual for more details on the results produced by each oper- ator. All of the binary operators group left-to-right within the same precedence level. For example, the commandmpexpr4*2<7returns 0. The &&,||, and?:operators have ``lazy evaluation'', just as in C, which means that operands are not evaluated if they are not needed to determine the outcome. For example, in the commandmpexpr{$v?[a]:[b]}only one of[a]or[b]will actually be evaluated, depending on the value of$v. Note, however, that this is only true if the entire ex- pression is enclosed in braces; otherwise the Tcl parser will evaluate both[a]and[b]before invoking theexprcommand.MATH FUNCTIONSMpexpr supports the following mathematical functions in expressions.xandyare integer or floating point values;i,jandcare integer val- ues; Math functions compatible withexpr:acos(x)Arc cosine ofx.asin(x)Arc sine ofx.atan(x)Arc tangent ofx.atan2(x,y)Arc tangent ofx/y.ceil(x)Least integral value greater than or equal tox.cos(x)Cosine ofx.cosh(x)Hyperbolic cosine ofx.exp(x)Exponential function e **x.floor(x)Greatest integral value less than or equal tox.fmod(x,y)Remainder ofxdivided byy.hypot(x,y)Euclidean distance of sqrt(x*x+y*y).log(x)Natural logarithm ofx.log10(x)Base-10 logarithm ofx.pow(x,y)xraised to theypower.sin(x)Sine ofx.sinh(x)Hyperbolic sine ofx.sqrt(x)Square root ofx.tan(x)Tangent ofx.tanh(x)Hyperbolic tangent ofx.abs(x)Returns the absolute value ofx.xmay be either inte- ger or floating-point, and the result is returned in the same form.double(x)Ifxis a floating value, returnsx, otherwise convertsxto floating and returns the converted value.int(x)Ifxis an integer value, returnsx, otherwise convertsxto integer by truncation and returns the converted value.round(x)Ifxis an integer value, returnsx, otherwise convertsxto integer by rounding and returns the converted value. Additionalmpexprfunctions:root(x,y)Theythroot ofx.frem(x,y)Remove all occurance of factoryfrom numberx.minv(x,y)Inverse ofxmoduloy.gcd(x,y)Greatest common divisor ofxandy.lcm(x,y)Least common multiple ofxandy.max(x,y)Maximum ofxandy.min(x,y)Minimum ofxandy.pi()Value of pi.fib(i)Fibonacci number of integeri.fact(i)Factorial of integeri.pfact(i)Product of prime numbers up to integeri.lfactor(i,c)Lowest prime factor of integeri, trying countctimes.iroot(i,j)Integer rootjof integeri.gcdrem(i,j)Relatively prime of greatest common divisior ofidi- vided byj.perm(i,j)Permutations ofitakingjat a time:i! / (i-j) !.comb(i,j)Combinations ofitakingjat a time:i! / (j! * (i-j) ! ) .prime(i,c)Return 0 ifiis not prime, return 1 ifiprobably is prime. Test for primality countctimes. The chance of a non-prime passing this test is less than (1/4)^count. For example, a count of 100 fails for only 1 in 10^60 numbers.relprime(i,j)Return 1 ifiandjare relatively prime to each other, 0 otherwise.TYPES, OVERFLOW, AND PRECISIONComputations are performed using arbitrary fixed and floating point values. Native machine values (int,long,IEEE754floatingpoint,etc.) and instructions are not used. Conversion among internal rep- resentations for integer, floating-point, and string operands is done automatically as needed. For arithmetic computations, integers are used until some floating-point number is introduced, after which float- ing-point is used. For example,mpexpr5/4returns 1, whilempexpr5/4.0mpexpr5/([stringlength"abcd"]+0.0)both return 1.25. Floating-point values are always returned with a ``.'' or an ``e'' so that they will not look like integer values. For example,mpexpr20.0/5.0returns ``4.0'', not ``4''. The global variablemp_precisiondetermines the number of significant digits that are retained during evaluation. Ifmp_precisionis unset then 17 digits of precision are used. The maximum value ofmp_preci-sionis 10000. Note that larger values formp_precisionwill require increasingly longer execution times. Settingmp_precisionto an ille- gal value will generate an error.STRING OPERATIONSString values may be used as operands of the comparison operators, al- though the expression evaluator tries to do comparisons as integer or floating-point when it can. If one of the operands of a comparison is a string and the other has a numeric value, the numeric operand is con- verted back to a string using the Csprintfformat specifier%dfor in- tegers and%gfor floating-point values. For example, the commandsmpexpr{"0x03">"2"}mpexpr{"0y"<"0x12"}both return 1. The first comparison is done using integer comparison, and the second is done using string comparison after the second operand is converted to the string ``18''. Because of Tcl's tendency to treat values as numbers whenever possible, it isn't generally a good idea to use operators like==when you really want string comparison and the values of the operands could be arbitrary; it's better in these cases to use thestringcomparecommand instead.mpformatformats a string in the style of Tcl's nativeformatcommand. Mpformat will interpret numeric arguments as arbitrary precision num- bers. Mpformat performs limited % substitution on the output string. The following may be specified:%[-][width[.precision]]formatChar-Specifies left justification; right justification is the de- fault.width.precisionSpecifies optional width and precision. Default precision is 8. Width and/or precision may be specified as*, in which the next argument will be used for the width or precision value.FormatcharacterandresultdFormat next argument as integer, truncating after the decimal point.fFormat next argument in decimal floating point.eFormat next argument in scientific notation.r,RFormat next argument as rational fraction x / y.NFormat next argument as numerator only of rational fraction x / y.DFormat next argument as denominator only of rational fraction x / y.oFormat next argument in octal format, with leading '0'; floating point argument formatted as octal rational fraction x / y.xFormat next argument in hexadecimal format, with leading '0x'; floating point formatted argument as hexadecimal rational frac- tion x / y.bFormat next argument in binary format, with leading '0b'; float- ing point argument formatted as binary rational fraction x / y.sFormat next argument as string.cFormat next argument as single character value.%Format single literal %.Othercharactersinformatstring\nFormat ASCII newline.\rFormat ASCII carriage return.\tFormat ASCII tab.\fFormat ASCII form feed.\vFormat ASCII vertical tab.\bFormat ASCII backspace.NOTESMpexpr is based on Tcl 7.6 'tclExpr.c' and David Bell's 'Calc' program. This man page is largely borrowed from Tcl 7.6 as well, as is the mp- expr test suite. See the files README and INSTALL for additional information. Tcl 7.6 is Copyright (c) 1987-1994 The Regents of the University of California and Copyright (c) 1994 Sun Microsystems, Inc. Calc is Copyright (c) 1994 David I. Bell.AUTHORTom Poindexter, tpoindex@nyx.net, Talus Technologies, Inc., Highlands Ranch, CO. http://www.nyx.net/~tpoindex Version 1.0 released November, 1998. Copyright 1998 Tom Poindexter. See the file 'LICENSE.TERMS' for addi- tional copyright and licensing terms. Tcl 8 January 1998 mpexpr(TCL)

NAME | SYNOPSIS | DESCRIPTION | OPERANDS | OPERATORS | MATH FUNCTIONS | TYPES, OVERFLOW, AND PRECISION | STRING OPERATIONS | NOTES | AUTHOR

Want to link to this manual page? Use this URL:

<https://www.freebsd.org/cgi/man.cgi?query=mpexpr&manpath=FreeBSD+13.0-RELEASE+and+Ports>