Release calc version 2.11.3t0

This commit is contained in:
Landon Curt Noll
2000-07-14 00:55:58 -07:00
parent 61dd47526f
commit ae2a752314
33 changed files with 2784 additions and 1556 deletions

View File

@@ -19,7 +19,7 @@
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#
# @(#) $Revision: 29.3 $
# @(#) $Id: Makefile,v 29.3 2000/06/07 14:02:33 chongo Exp $
# @(#) $Id: Makefile,v 29.3 2000/06/07 14:02:33 chongo Exp chongo $
# @(#) $Source: /usr/local/src/cmd/calc/help/RCS/Makefile,v $
#
# Under source code control: 1991/07/23 06:47:57
@@ -141,29 +141,30 @@ BLT_HELP_FILES= ${BLT_HELP_FILES_3} ${BLT_HELP_FILES_5} \
#
DETAIL_HELP= abs access acos acosh acot acoth acsc acsch address agd append \
appr arg argv arrow asec asech asin asinh assign atan atan2 atanh \
avg base bit blk blkcpy blkfree blocks bround btrunc calclevel ceil \
cfappr cfsim char cmdbuf cmp comb conj cos cosh cot coth count cp \
csc csch ctime delete den dereference det digit digits dp epsilon \
errcount errmax errno error eval exp fact factor fclose fcnt feof \
ferror fflush fgetc fgetfield fgetline fgets fgetstr fib files floor \
fopen forall fprintf fputc fputs fputstr frac free freeglobals \
freeredc freestatics frem freopen fscan fscanf fseek fsize ftell \
gcd gcdrem gd getenv hash head highbit hmean hnrmod hypot ilog \
ilog10 ilog2 im indices inputlevel insert int inverse iroot isassoc \
isatty isblk isconfig isdefined iserror iseven isfile ishash isident \
isint islist ismat ismult isnull isnum isobj isobjtype isodd isprime \
isptr isqrt isrand israndom isreal isrel issimple issq isstr istype \
jacobi join lcm lcmfact lfactor ln lowbit ltol makelist matdim \
matfill matmax matmin matsum mattrace mattrans max md5 memsize meq \
min minv mmin mne mod modify name near newerror nextcand nextprime \
norm null num oldvalue ord param perm pfact pi pix places pmod polar \
poly pop popcnt power prevcand prevprime printf prompt protect ptest \
push putenv quo quomod rand randbit random randombit randperm rcin \
rcmul rcout rcpow rcsq re remove reverse rewind rm root round rsearch \
runtime saveval scale scan scanf search sec sech seed segment select \
sgn sha sha1 sin sinh size sizeof sort sqrt srand srandom ssq str \
strcat strerror strlen strpos strprintf strscan strscanf substr \
sum swap system tail tan tanh test time trunc xor
avg base bernoulli bit blk blkcpy blkfree blocks bround btrunc \
calclevel ceil cfappr cfsim char cmdbuf cmp comb conj cos cosh \
cot coth count cp csc csch ctime delete den dereference det digit \
digits dp epsilon errcount errmax errno error eval exp fact factor \
fclose fcnt feof ferror fflush fgetc fgetfield fgetline fgets fgetstr \
fib files floor fopen forall fprintf fputc fputs fputstr frac free \
freebernoulli freeglobals freeredc freestatics frem freopen fscan \
fscanf fseek fsize ftell gcd gcdrem gd getenv hash head highbit \
hmean hnrmod hypot ilog ilog10 ilog2 im indices inputlevel insert \
int inverse iroot isassoc isatty isblk isconfig isdefined iserror \
iseven isfile ishash isident isint islist ismat ismult isnull isnum \
isobj isobjtype isodd isprime isptr isqrt isrand israndom isreal \
isrel issimple issq isstr istype jacobi join lcm lcmfact lfactor ln \
lowbit ltol makelist matdim matfill matmax matmin matsum mattrace \
mattrans max md5 memsize meq min minv mmin mne mod modify name \
near newerror nextcand nextprime norm null num oldvalue ord param \
perm pfact pi pix places pmod polar poly pop popcnt power prevcand \
prevprime printf prompt protect ptest push putenv quo quomod rand \
randbit random randombit randperm rcin rcmul rcout rcpow rcsq re \
remove reverse rewind rm root round rsearch runtime saveval scale \
scan scanf search sec sech seed segment select sgn sha sha1 sin \
sinh size sizeof sort sqrt srand srandom ssq str strcat strerror \
strlen strpos strprintf strscan strscanf substr sum swap system \
tail tan tanh test time trunc xor
# This list is of files that are clones of DETAIL_HELP files. They are
# built from DETAIL_HELP files.

67
help/bernoulli Normal file
View File

@@ -0,0 +1,67 @@
NAME
bernoulli - Bernoulli number
SYNOPSIS
bernoulli(n)
TYPES
n integer, n < 2^31 if even
return rational
DESCRIPTION
Returns the Bernoulli number with index n, i.e. the coefficient B_n in
the expansion
t/(exp(t) - 1) = Sum B_n * t^n/n!
bernouuli(n) is zero both for n < 0 and for n odd and > 2.
When bernoulli(n) is computed for positive even n, the values for
n and smaller positive even indices are stored in a table so that
a later call to bernoulli(k) with 0 <= k < n will be executed quickly.
Considerable runtime and memory are required for calculating
bernoulli(n) for large even n. For n = 1000, the numerator has
1779 digits, the denominator 9 digits.
The memory used to store calculated bernoulli numbers is freed by
freebernoulli().
EXAMPLE
> config("mode", "frac"),;
> for (n = 0; n <= 6; n++) print bernoulli(n),; print;
1 -1/2 1/6 0 -1/30 0 1/42
LIMITS
n < 2^31-1
LINK LIBRARY
NUMBER *qbernoulli(long n)
SEE ALSO
euler, freebernoulli, catalan, comb, fact, perm
## Copyright (C) 2000 Ernest Bowen
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
## as published by the Free Software Foundation.
##
## Calc is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
## Public License for more details.
##
## A copy of version 2.1 of the GNU Lesser General Public License is
## distributed with calc under the filename COPYING-LGPL. You should have
## received a copy with calc; if not, write to Free Software Foundation, Inc.
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: sin,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/sin,v $
##
## Under source code control: 2000/07/13
## File existed as early as: 2000
##
## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/

View File

@@ -1,121 +1,197 @@
Function definitions
NAME
define - command keyword to start a function definition
Function definitions are introduced by the 'define' keyword.
Other than this, the basic structure of an ordinary definition
is like in that in C: parameters are specified for the function
within parenthesis, the function body is introduced by a left brace,
variables may declared for the function, statements implementing the
function may follow, any value to be returned by the function is specified
by a return statement, and the function definition is ended with a
right brace.
SYNTAX
define fname([param_1 [= default_1], ...]) = [expr]
define fname([param_1 [= default_1], ...]) { [statement_1 ... ] }
There are some subtle differences, however. The types of parameters
and variables are not defined at compile time, and may vary during
execution and be different in different calls to the function. For
example, a two-argument function add may be defined by
TYPES
fname identifier, not a builtin function name
param_1, ... identifiers, no two the same
default_1, ... expressions
expr expression
statement_1, ... statements
define add(a,b) {
return a + b;
}
DESCRIPTION
The intention of a function definition is that the identifier fname
becomes the name of a function which may be called by an expression
of the form fname(arg_1, arg_2, ...), where arg_1, arg_2, ... are
expressions (including possibly blanks, which are treated as
null values). Evaluation of the function begins with evaluation
of arg_1, arg_2, ...; then, in increasing order of i, if arg_i is
null-valued and "= default_i" has been included in the definition,
default_i is evaluated and its value becomes the value of arg_i.
The instructions in expr or the listed statements are then executed
with each occurrence of param_i replaced by the value obtained
for arg_i.
and be called with integer, fractional, or complex number values for a
and b, or, under some compatibility conditions, matrices or objects.
Any variable, not already defined as global, used in a definition has
to be declared as local, global or static, and retains this character
until its scope is terminated by the end of the definition, the end of
the file being read or some other condition (see help variable for
details).
In a call, arg_i may be preceded by a backquote (`) to indicate that
evaluation of arg_i is not to include a final evaluation of an lvalue.
For example, suppose a function f and a global variable A have been
defined by:
For example, the following function computes the factorial of n, where
we may suppose it is to be called only with positive integral values
for n:
define f(x) = (x = 3);
global mat A[3];
define factorial(n)
{
local ans;
If g() is a function that evaluates to 2:
ans = 1;
while (n > 1)
ans *= n--;
return ans;
}
f(A[g()]);
(In calc, this definition is unncessary since there is a built-in
function fact(n), also expressible as n!, which returns the factorial
of n.)
assigns the value of A[2] to the parameter x and then assigns the
value 3 to x:
Any functions used in the body of the definition need not have already
been defined; it is sufficient that they have been defined when they are
encountered during evaluation when the function is called.
f(`A[g()]);
If a function definition is sufficiently simple and does not require
local or static variables, it may be defined in shortened manner by
using an equals sign following by an expression involving some or all
of the parameters and already existing global variables.
has essentially the effect of assigning A[2] as an lvalue to x and
then assigning the value 3 to A[2]. (Very old versions of calc
achieved the same result by using '&' as in f(&A[g()]).)
In this case, the definition is terminated by a newline character
(which may be preceded by a semicolon), and the value the function
returns when called will be determined by the specified expression.
Loops and "if" statements are not allowed (but ? : expressions and the
logical operators ||, && and ! are permitted). As an example, the
average of two numbers could be defined as:
The number of arguments arg_1, arg_2, ... in a call need not equal the
number of parameters. If there are fewer arguments than parameters,
the "missing" values are assigned the null value.
define average(a, b) = (a + b) / 2;
In the definition of a function, the builtin function param(n)
provides a way of referring to the parameters. If n (which may
result from evaluating an expreession) is zero, it returns the number
of arguments in a call to the function, and if 1 <= n <= param(0),
param(n) refers to the parameter with index n.
(Again, this function is not necessary, as the same result is
returned by the builtin function avg() when called with the
two arguments a, b.)
If no error occurs and no quit statement or abort statement is
encountered during evaluation of the expression or the statements,
the function call returns a value. In the expression form, this is
simply the value of the expression.
Function definitions can be very complicated. Functions may be
defined on the command line if desired, but editing of partial
functions is not possible past a single line. If an error is made
on a previous line, then the function must be finished (with probable
errors) and reentered from the beginning. Thus for complicated
functions, it is best to use an editor to create the definition in a
file, and then enter the calculator and read in the file containing
the definition.
In the statement form, if a return statement is encountered,
the "return" keyword is to be either immediately followed by an
expression or by a statement terminator (semicolon or rightbrace);
in the former case, the expression is evaluated, evaluation of
the function ceases, and the value obtained for the expression is
returned as the "value of the function"; in the no-expression case,
evaluation ceases immediately and the null-value is returned.
The parameters of a function can be referenced by name, as in
normal C usage, or by using the 'param' function. This function
returns the specified parameter of the function it is in, where
the parameters are numbered starting from 1. The total number
of parameters to the function is returned by using 'param(0)'.
Using this function allows you to implement varargs-like routines
which can handle up to 100 calling parameters. For example:
In the expression form of definition, the end of the expression expr
is to be indicated by either a semicolon or a newline not within
a part enclosed by parentheses; the definition may extend over
several physical lines by ending each line with a '\' character or by
enclosing the expression in parentheses. In interactive mode, that
a definition has not been completed is indicated by the continuation
prompt. A ctrl-C interrupt at this stage will abort the definition.
define sc()
{
local s, i;
If the expr is omitted from an expression definition, as in:
s = 0;
for (i = 1; i <= param(0); i++)
s += param(i)^3;
return s;
}
define h() = ;
defines a function which returns the sum of the cubes of all its
parameters.
any call to the function will evaluate the arguments and return the
null value.
Any identifier other than a reserved word (if, for, etc.) and the
name of a builtin function (abs, fact, sin, etc.) can be used when
defining a new function or redefining an existing function.
In the statement form, the definition ends when a matching right
brace completes the "block" started by the initial left brace.
Newlines within the block are treated as white space; statements
within the block end with a ';' or a '}' matching an earlier '{'.
An indication of how a user-defined function is stored may be obtained
by using the "show opcodes" command. For example:
If a function with name fname had been defined earlier, the old
definition has no effect on the new definition, but if the definition
is completed successfully, the new definition replaces the old one;
otherwise the old definition is retained. The number of parameters
and their names in the new definiton may be quite different from
those in the old definition.
> global alpha
> define f(x) = 5 + alpha * x
"f" defined
> show opcodes f
0: NUMBER 5
2: GLOBALADDR alpha
4: PARAMADDR 0
6: MUL
7: ADD
8: RETURN
An attempt at a definition may fail because of scanerrors as the
definition is compiled. Common causes of these are: bad syntax,
using identifiers as names of variables not yet defined. It is
not a fault to have in the definition a call to a function that has
not yet been defined; it is sufficient that the function has been
defined when a call is made to the function.
After fname has been defined, the definition may be removed by the command:
## Copyright (C) 1999 Landon Curt Noll
undefine fname
The definitions of all user-defined functions may be removed by:
undefine *
If bit 0 of config("resource_debug") is set and the define command is
at interactive level, a message saying that fname has been defined
or redefined is displayed. The same message is displayed if bit 1
of config("resource_debug") is set and the define command is read
from a file.
The identifiers used for the parameters in a function definition do
not form part of the completed definition. For example,
define f(a,b) = a + b;
define g(alpha, beta) = alpha + beta;
result in identical code for the functions f, g.
If config("trace") & 8 is nonzero, the opcodes of a newly defined
function are displayed on completion of its definition, parameters
being specified by names used in the definition. For example:
> config("trace", 8),
> define f(a,b) = a + b
0: PARAMADDR a
2: PARAMADDR b
4: ADD
5: RETURN
f(a,b) defined
The opcodes may also be displayed later using the show opcodes command;
parameters will be specified by indices instead of by names. For example:
> show opco f
0: PARAMADDR 0
2: PARAMADDR 1
4: ADD
5: RETURN
When a function is defined by the statement mode, the opcodes normally
include DEBUG opcodes which specify statement boundaries at which
SIGINT interruptions are likely to be least risky. Inclusion of
the DEBUG opcodes is disabled if config("trace") & 2 is nonzero.
For details, see help interrupt.
While config("trace") & 1 is nonzero, the opcodes are displayed as
they are being evaluated. The current function is identified by its
name, or "*" in the case of a command-line and "**" in the case of
an eval(str) evaluation.
When a function is called, argument values may be of any type for
which the operations and any functions used within the body of the
definition can be executed. For example, whatever the intention at
the time they were defined, the functions f1(), f2() defined above
may be called with integer, fractional, or complex-number values, or
with both arguments strings, or under some compatibility conditions,
matrices or objects.
EXAMPLE
> define f(a,b) = 2*a + b;
> define g(alpha, beta)
>> {
>> local a, pi2;
>>
>> pi2 = 2 * pi();
>> a = sin(alpha % pi2);
>> if (a > 0.0) {
>> return a*beta;
>> }
>> if (beta > 0.0) {
>> a *= cos(-beta % pi2);
>> }
>> return a;
>> }
LIMITS
The number of arguments in a function-call cannot exceed 100.
LIBRARY
none
SEE ALSO
param, variable, undefine, show
## Copyright (C) 2000 David I. Bell, Landon Curt Noll and Ernest Bowen
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
@@ -132,8 +208,9 @@ Function definitions
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: define,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/define,v $
## @(#) $Id: sin,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/sin,v $
##
##
## Under source code control: 1991/07/21 04:37:18
## File existed as early as: 1991

49
help/freebernoulli Normal file
View File

@@ -0,0 +1,49 @@
NAME
freebernoulli - free stored Benoulli numbers
SYNOPSIS
freebernoulli()
TYPES
return none
DESCRIPTION
The memory used to store calculated bernoulli numbers is freed by
freebernoulli().
EXAMPLE
> freebernoulli();
LIMITS
none
LINK LIBRARY
void qfreebern(void);
SEE ALSO
bernoulli
## Copyright (C) 2000 Ernest Bowen
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
## as published by the Free Software Foundation.
##
## Calc is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
## Public License for more details.
##
## A copy of version 2.1 of the GNU Lesser General Public License is
## distributed with calc under the filename COPYING-LGPL. You should have
## received a copy with calc; if not, write to Free Software Foundation, Inc.
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: sin,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/sin,v $
##
## Under source code control: 2000/07/13
## File existed as early as: 2000
##
## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/

View File

@@ -15,10 +15,13 @@ Interrupts
[Abort level n]
where n ranges from 1 to 3. For n equal to 1, the calculator will
abort calculations at the next statement boundary. For n equal to 2,
the calculator will abort calculations at the next opcode boundary.
For n equal to 3, the calculator will abort calculations at the next
lowest level arithmetic operation boundary.
abort calculations at the next statement boundary specified by an
ABORT opcode as described below. For n equal to 2, the calculator
will abort calculations at the next opcode boundary. For n equal to 3,
the calculator will abort calculations at the next attempt to allocate
memory for the result of an integer arithmetic operation; this
level may be appropriate for stopping a builtin operation like
inversion of a large matrix.
If a final interrupt is given when n is 3, the calculator will
immediately abort the current calculation and longjmp back to the
@@ -27,8 +30,77 @@ Interrupts
be done as a last resort. You are advised to quit the calculator
after this has been done.
## Copyright (C) 1999 Landon Curt Noll
##
ABORT opcodes
If config("trace") & 2 is zero, ABORT opcodes are introduced at
various places in the opcodes for evaluation of command lines
and functions defined by "define ... { ... }" commands. In the
following, config("trace") has been set equal to 8 so that opcodes
are displayed when a function is defined. The function f(x)
evaluates x + (x - 1) + (x - 2) + ... until a zero term is
encountered. If f() is called with a negative or fractional x,
the calculation is never completed and to stop it, an interruption
(on many systems, by ctrl-C) will be necessary.
> config("trace", 8),
> define f(x) {local s; while (x) {s += x--} return s}
0: DEBUG line 2
2: PARAMADDR x
4: JUMPZ 19
6: DEBUG line 2
8: LOCALADDR s
10: DUPLICATE
11: PARAMADDR x
13: POSTDEC
14: POP
15: ADD
16: ASSIGNPOP
17: JUMP 2
19: DEBUG line 2
21: LOCALADDR s
23: RETURN
f(x) defined
(The line number following DEBUG refers to the line in the file
from which the definition is read.) If an attempt is made to
evaluate f(-1), the effect of the DEBUG at opcode 6 ensures that
a single SIGINT will stop the calculation at a start of
{s += x--} loop. In interactive mode, with ^C indicating
input of ctrl-C, the displayed output is as in:
> f(-1)
^C
[Abort level 1]
"f": line 2: Calculation aborted at statement boundary
The DEBUG opcodes are disabled by nonzero config("trace") & 2.
Changing config("trace") to achieve this, and defining g(x) with
the same definition as for f(x) gives:
> define g(x) {local s; while (x) {s += x--} return s}
0: PARAMADDR x
2: JUMPZ 15
4: LOCALADDR s
6: DUPLICATE
7: PARAMADDR x
9: POSTDEC
10: POP
11: ADD
12: ASSIGNPOP
13: JUMP 0
15: LOCALADDR s
17: RETURN
g(x) defined
If g(-1) is called, two interrupts are necessary, as in:
> g(-1)
^C
[Abort level 1]
^C
[Abort level 2]
"g": Calculation aborted in opcode
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
## as published by the Free Software Foundation.
@@ -44,7 +116,7 @@ Interrupts
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## @(#) $Revision: 29.2 $
## @(#) $Id: interrupt,v 29.2 2000/06/07 14:02:33 chongo Exp $
## @(#) $Id: interrupt,v 29.2 2000/06/07 14:02:33 chongo Exp chongo $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/interrupt,v $
##
## Under source code control: 1991/07/21 04:37:21

View File

@@ -1,62 +1,264 @@
Calc shell scripts
------------------
If an executable file begins with:
There are several ways calc may be used in shell scripts. The
syntax for these varies widely for different shells and systems,
but common to most are commands like echo, if, for, goto, shift,
and exit, as well as the accessing of environment parameters, shell
variables, and command-line arguments.
#!/usr/local/bin/calc -S [-other_flags ...]
As a simple example, assuming a C or Bourne shell, let add be a
file containing just one line:
the rest of the file will be processed in shell script mode.
Note that -S (UPPER CASE -S) must be the first -flag on the
``#!'' line. Any other optional ``-other_flags'' must come
after the -S.
calc -q -- $1 + $2
In shell script mode the contents of the file are evaluated
and executed as if they were processed by the read command.
Any optional ``-other_flags'' will by parsed first followed
by any arguments given shell script itself.
Then:
In shell script mode, -s (lower case -s) is always assumed.
In addition, -d and -p are automatically set if -i is not
given.
./add 1.23 4.56
For example, if the file /tmp/mersenne:
should respond with the display of:
#!/usr/local/bin/calc -S -q
#
# mersenne - an example of a calc shell script file
5.9
/* parse args */
if (argv() != 1) {
fprintf(files(2), "usage: %s exp\n", config("program"));
abort "must give one exponent arg";
}
The "-q" was included in the command to avoid reading of any
start-up calc files which could contain commands not wanted
here. The "--" indicates that there are no more options;
without it, if $1 began with '-', calc would interpret it as
the first character of another option. To execute the file,
the strings "1.23" and "4.56" were assigned to $1 and $2, so
calc was in effect asked to evaluate the string "1.23 + 4.56".
/* print the mersenne number */
print "2^": argv(0) : "-1 =", 2^eval(argv(0))-1;
By making add executable by a command like:
is made an executable file by:
chmod u+x add
chmod +x /tmp/mersenne
the command used here may be simplified to:
then the command line:
./add 1.23 4.56
/tmp/mersenne 127
Here we shall assume that any script we refer to has been made
executable in this way.
will print:
Because $1 and $2, and instructions in the script, are to read
by calc as expressions or commands, they may be much more
complicated than in the above example, but if they involve
characters with special interpretations by the shell (spaces
for word separation, * or ? or [ ...] for file-name expansion,
! (without immediately following space) for history expansion,
( ... ) for shell-function arguments, { ... } for brace
expansion, $ for parameter or variable expansion, <, <<, >, >>
for redirection of input or output, etc.) it will usually be
necessary to quote or escape tho characters, or usually more
conveniently, quote whole expressions with single or double
quotes.
2^127-1 = 170141183460469231731687303715884105727
For example, the add script should have no problem with
commands like:
Note that because -s is assumed in shell script mode and
non-dashed args are made available as strings via the argv()
builtin function. Therefore:
./add "sqrt(2)" "3 * 4"
2^eval(argv(0))-1
./add "mat A[2,2] = {1,2,3,4}" "A^2"
will print the decimal value of 2^n-1 but
./add "2 + 3i" "(3 + 4i)^2"
2^argv(0)-1
If the shell arguments are to be integers, one could use
scripts like the following with arithmetic expansion
for the bash and ksh:
will not.
declare -i a=$1
declare -i b=$2
calc -q -- $a + $b
and for csh:
@ a = $1
@ b = $2
calc -q -- $a + $b
Specifying the shell for a script may be done by including
in the script a first line with the "magic number" "#!" and
the full file path for the shell as in:
#!/bin/bash
declare -i a=$1
declare -i b=$2
calc -q -- $a + $b
For a script to multiply rather than add two expressions, one
could have a file mul with the one line:
calc -q -- $1 \* $2
or:
calc -q -- "$1 * $2"
which will work so long as $1 and $2 are literal numbers, but
will not work for:
./mul 2+3 4
or:
./mul "2 + 3" 4
both of which calc interprets as evaluating 2 + 3 * 4. What should
work for most shells is:
calc -q -- "($1) * ($2)"
For adding an arbitrary number of expressions that evaluate to
rational numbers expressible with at most 20 decimal places,
simple shell script could be used:
s=0
for i do
s=`calc -q -- $s + $i`
done
echo sum = $s
This is not particularly efficient since it calls calc once for
each argument. Also, a more serious script would permit more
general numbers.
Another way of handling a sum of several expressions is with
the script addall2 with a here document:
calc "-q -s" $* << +
global i, n, s;
n = argv();
for (i = 0; i < n; i++)
s += eval(argv(i));
print "sum =", s;
+
In executing the command:
./addall2 2 3 4
the $* in ths script expands to 2 3 4, and because of the "-s"
in the options, calc starts with argv(0) = "2", argv(1) = "3",
argv(2)= "4". As there is only one calc process involved and
the eval() function accepts as argument any string that
represents the body of a calc function, the strings argv(0),
argv(1), ... could evaluate to any value types for which the
additions to be performed are defined, and variables defined in
one argv() can be used in later arguments.
For systems that support interpreter files, essentially the
same thing may be done more efficiently by using calc as an
interpreter. Assuming the full path for calc is
/usr/bin/calc, one could use the file addall3 with contents
#!/usr/bin/calc -q -s -f
global i, n, s;
n = argv();
for (i = 1; i <= n; i++)
s += eval(argv(i));
print "sum =", s;
After the command:
addall3 2 3 4
the arguments calc receives are argv(0) = "addall3", argv(1) =
"2", argv(3) = "3", argv(4) = "4".
Another kind of script that can be useful is sqrts1:
calc -q 'global s; while (scanf("%s", s) == 1) print sqrt(eval(s));'
or what is essentially an interpreter equivalent sqrts2:
#!/usr/bin/calc -q -f
global s;
while (scanf('%s', s) == 1)
print sqrt(eval(s));
If sqrts is either of these scripts, the command:
echo 27 2+3i | sqrts
or, if datafile contains the one line:
27 2+3i
or the two lines:
27
2+3i
either:
cat datafile | ./sqrts
or:
./sqrts < datafile
should display the square-roots of 27 and 2+3i. The output could
be piped to another command by | or directed to a file by use of
> or >>.
With no specified input, either sqrts1 or sqrts2 will wait
without any prompt for input from the keyboard and as each line
is completed display the square-roots of the expressions
entered. Exit can be achieved by entering exit or entering
ctrl-D (interpreted as EOF) rather than a line of input.
One advantage of an interpreter file like sqrts2 (which has only
options, but neither "-s" nor "--" in its first line) is that it
can be invoked with further options as in
echo 2 3 4 | ./sqrts2 -i -D 32
An advantage of non-interpreter files is that they can use shell
features. For example, for unquoted arguments or arguments in
double quotes parameter expansion (indicated by unquoted '$') and
command substitution (using backquotes) occur before lines are
compiled by calc. For example, if doit is an executable
script with contents
calc -q -- "$1($2)"
it may be used as in:
./doit sqrt 7
and:
./doit exp 7
to display the values of sqrt(7) and exp(7). The "--" prevents a
leading '-' in the $1 argument as indicating one or more additional
options. E.g., without the "--" in doit,
./doit -sqrt 7
would be interpreted as:
calc -q "-sqrt(7)"
in which the dash in the quoted part would be taken as indicating a
list of options -s, -q, -r, etc.; this would give an "illegal option"
error as calc has no -r option.
In invoking the doit script it is not necessary that $1 expand to a
calc function name and $2 to an expression; all that is required is
that:
$1($2)
expands to a string that calc will recognize as a command. E.g.:
./doit "define f(x) = x^2; 2 + mod" "f(7), 6"
does the same as:
calc -q -- "define f(x) = x^2; 2 + mod(f(7), 6)"
Essentially the same is achieved by the contents of doit is changed to:
calc -q -p -- << +
$1($2)
+
The "-p" stops calc going interactive; without it the effect would be
be the same as that of a script with the one line:
calc -q -i -- "$1($2)"
For more information use the following calc commands:
@@ -65,7 +267,7 @@ For more information use the following calc commands:
help config
help cscript
## Copyright (C) 1999 Landon Curt Noll
## Copyright (C) 2000 Landon Curt Noll and Ernest Bowen
##
## Calc is open software; you can redistribute it and/or modify it under
## the terms of the version 2.1 of the GNU Lesser General Public License
@@ -82,7 +284,7 @@ For more information use the following calc commands:
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
##
## @(#) $Revision: 29.3 $
## @(#) $Id: script,v 29.3 2000/06/07 14:02:33 chongo Exp $
## @(#) $Id: script,v 29.3 2000/06/07 14:02:33 chongo Exp chongo $
## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/script,v $
##
## Under source code control: 1999/11/30 05:29:48
@@ -90,3 +292,4 @@ For more information use the following calc commands:
##
## chongo <was here> /\oo/\ http://www.isthe.com/chongo/
## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/