37 * File existed as early as: 1991 * * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ /* * Calculate pi within the specified epsilon using the quartic convergence * iteration. */ define qpi(epsilon) { local niter, yn, ym, tm, an, am, t, tn, sqrt2, epsilon2, count, digits; local bits, bits2; if (isnull(epsilon)) epsilon = epsilon(); digits = digits(1/epsilon); if (digits <= 8) { niter = 1; epsilon = 1e-8; } else if (digits <= 40) { niter = 2; epsilon = 1e-40; } else if (digits <= 170) { niter = 3; epsilon = 1e-170; } else if (digits <= 693) { niter = 4; epsilon = 1e-693; } else { niter = 4; t = 693; while (t < digits) { ++niter; t *= 4; } } epsilon2 = epsilon/(digits/10 + 1); digits = digits(1/epsilon2); sqrt2 = sqrt(2, epsilon2); bits = abs(ilog2(epsilon)) + 1; bits2 = abs(ilog2(epsilon2)) + 1; yn = sqrt2 - 1; an = 6 - 4 * sqrt2; tn = 2; for (count = 0; count < niter; ++count) { ym = yn; am = an; tn *= 4; t = sqrt(sqrt(1-ym^4, epsilon2), epsilon2); yn = (1-t)/(1+t); an = (1+yn)^4*am-tn*yn*(1+yn+yn^2); yn = bround(yn, bits2); an = bround(an, bits2); } return (bround(1/an, bits)); } /* * Print digits of PI forever, neatly formatted, using calc. * * Written by Klaus Alexander Seistrup * on a dull Friday evening in November 1999. * * Inspired by an algorithm conceived by Lambert Meertens. * * See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, * published by Prentice-Hall (UK) Ltd., 1990. * */ define piforever() { local k = 2; local a = 4; local b = 1; local a1 = 12; local b1 = 4; local a2, b2, p, q, d, d1; local stdout = files(1); local first = 1, row = -1, col = 0; while (1) { /* * Next approximation */ p = k * k; q = k + ++k; a2 = a; b2 = b; a = a1; a1 = p * a2 + q * a1; b = b1; b1 = p * b2 + q * b1; /* * Print common digits */ d = a // b; d1 = a1 // b1; while (d == d1) { if (first) { printf("%d.", d); first = 0; } else { if (!(col % 50)) { printf("\n"); col = 0; if (!(++row % 20)) { printf("\n"); row = 0; } } printf("%d", d); if (!(++col % 10)) printf(" "); } a = 10 * (a % b); a1 = 10 * (a1 % b1); d = a // b; d1 = a1 // b1; } fflush(stdout); } } /* * unixfrac - represent a fraction as a sum of distince unit fractions * * Copyright (C) 1999 David I. Bell * * 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. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @(#) $Revision: 30.1 $ * @(#) $Id: unitfrac.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $ * @(#) $Source: /usr/local/src/cmd/calc/cal/RCS/unitfrac.cal,v $ * * Under source code control: 1990/02/15 01:50:38 * File existed as early as: before 1990 * * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ /* * Represent a fraction as sum of distinct unit fractions. * The output is the unit fractions themselves, and in square brackets, * the number of digits in the numerator and denominator of the value left * to be found. Numbers larger than 3.5 become very difficult to calculate. */ define unitfrac(x) { local d, di, n; if (x <= 0) quit "Non-positive argument"; d = 2; do { n = int(1 / x) + 1; if (n > d) d = n; di = 1/d; print ' [': digits(num(x)): '/': digits(den(x)): ']',, di; x -= di; d++; } while ((num(x) > 1) || (x == di) || (x == 1)); print ' [1/1]',, x; } /* * seedrandom - seed the cryptographically strong Blum generator * * Copyright (C) 1999 Landon Curt Noll * * 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. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @(#) $Revision: 30.1 $ * @(#) $Id: seedrandom.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $ * @(#) $Source: /usr/local/src/cmd/calc/cal/RCS/seedrandom.cal,v $ * * Under source code control: 1996/01/01 08:21:00 * File existed as early as: 1996 * * chongo /\oo/\ http://www.isthe.com/chongo/ * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ /* * The period of Blum generators with modulus 'n=p*q' (where p and * q are primes 3 mod 4) is: * * lambda(n) = lcm(factors of p-1 & q-1) * * One can construct a generator with a maximal period when * 'p' and 'q' have the fewest possible factors in common. * The quickest way to select such primes is only use 'p' * and 'q' when '(p-1)/2' and '(q-1)/2' are both primes. * This function will seed the random() generator that uses * such primes. * * given: * seed1 - a large random value (at least 10^20 and perhaps < 10^314) * seed2 - a large random value (at least 10^20 and perhaps < 10^314) * size - min Blum modulus as a power of 2 (at least 32, perhaps >= 512) * trials - number of ptest() trials (default 25) * * returns: * the previous random state * * NOTE: The [10^20, 10^314) range comes from the fact that the 13th internal * modulus is ~10^315. We want the lower bound seed to be reasonably big. */ define seedrandom(seed1, seed2, size, trials) { local p; /* first Blum prime */ local fp; /* prime co-factor of p-1 */ local sp; /* min bit size of p */ local q; /* second Blum prime */ local fq; /* prime co-factor of q-1 */ local sq; /* min bit size of q */ local n; /* Blum modulus */ local binsize; /* smallest power of 2 > n=p*q */ local r; /* initial quadratic residue */ local random_state; /* the initial rand state */ local random_junk; /* rand state that is not needed */ local old_state; /* old random state to return */ /* * firewall */ if (!isint(seed1)) { quit "1st arg (seed1) is not an int"; } if (!isint(seed2)) { quit "2nd arg (seed2) is not an int"; } if (!isint(size)) { quit "3rd arg (size) is not an int"; } if (!isint(trials)) { trials = 25; } if (digits(seed1) <= 20) { quit "1st arg (seed1) must be > 10^20 and perhaps < 10^314"; } if (digits(seed2) <= 20) { quit "2nd arg (seed2) must be > 10^20 and perhaps < 10^314"; } if (size < 32) { quit "3rd arg (size) needs to be >= 32 (perhaps >= 512)"; } if (trials < 1) { quit "4th arg (trials) must be > 0"; } /* * determine the search parameters */ ++size; /* convert power of 2 to bit length */ sp = int((size/2)-(size*0.03)+1); sq = size - sp; /* * find the first Blum prime */ random_state = srandom(seed1, 13); do { do { fp = nextcand(2^sp+randombit(sp), 1, 1, 3, 4); p = 2*fp+1; } while (ptest(p,1,0) == 0); } while(ptest(p, trials) == 0 || ptest(fp, trials) == 0); if (config("resource_debug") & 8) { print "/* 1st Blum prime */ p=", p; } /* * find the 2nd Blum prime */ random_junk = srandom(seed2, 13); do { do { fq = nextcand(2^sq+randombit(sq), 1, 1, 3, 4); q = 2*fq+1; } while (ptest(q,1,0) == 0); } while(ptest(q, trials) == 0 || ptest(fq, trials) == 0); if (config("resource_debug") & 8) { print "/* 2nd Blum prime */ q=", q; } /* * seed the Blum generator */ n = p*q; /* the Blum modulus */ binsize = highbit(n)+1; /* smallest power of 2 > p*q */ r = pmod(rand(1< 0) { if (iseven(x)) { static a5100 = x; a5100++; } else { static b5100 = x; b5100++; } } global a5100 = a5100, b5100 = b5100; } /* * sumsq - find unique two positive integers whose squares sum to a given prime * * Copyright (C) 1999 David I. Bell * * 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. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @(#) $Revision: 30.1 $ * @(#) $Id: sumsq.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $ * @(#) $Source: /usr/local/src/cmd/calc/cal/RCS/sumsq.cal,v $ * * Under source code control: 1990/02/15 01:50:37 * File existed as early as: before 1990 * * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ /* * Determine the unique two positive integers whose squares sum to the * specified prime. This is always possible for all primes of the form * 4N+1, and always impossible for primes of the form 4N-1. */ define ss(p) { local a, b, i, p4; if (p == 2) { print "1^2 + 1^2 = 2"; return; } if ((p % 4) != 1) { print p, "is not of the form 4N+1"; return; } if (!ptest(p, min(p-2, 10))) { print p, "is not a prime"; return; } p4 = (p - 1) / 4; i = 2; do { a = pmod(i++, p4, p); } while ((a^2 % p) == 1); b = p; while (b^2 > p) { i = b % a; b = a; a = i; } print a : "^2 +" , b : "^2 =" , a^2 + b^2; } /* * pollard - factor using Pollard's p-1 method * * Copyright (C) 1999 David I. Bell * * 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. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @(#) $Revision: 30.1 $ * @(#) $Id: pollard.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $ * @(#) $Source: /usr/local/src/cmd/calc/cal/RCS/pollard.cal,v $ * * Under source code control: 1991/05/22 21:56:37 * File existed as early as: 1991 * * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ define pfactor(N, B, ai, af) { local a, k, i, d; if (isnull(B)) B = 1000; if (isnull(ai)) ai = 2; if (isnull(af)) af = ai + 20; k = lcmfact(B); d = lfactor(N, B); if (d > 1) return d; for (a = ai; a <= af; a++) { i = pmod(a, k, N); d = gcd(i - 1, N); if ((d > 1) && (d != N)) return d; } return 1; } /* * prompt - eemonstration of some uses of prompt() and eval() * * Copyright (C) 1999 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. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @(#) $Revision: 30.1 $ * @(#) $Id: prompt.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $ * @(#) $Source: /usr/local/src/cmd/calc/cal/RCS/prompt.cal,v $ * * Under source code control: 1995/12/18 04:43:25 * File existed as early as: 1995 * * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ */ /* * Demonstration of some uses of prompt() and eval(). * * adder() simulates a simple adding machine: starting with sum = 0, * each number entered in response to the ? prompt is added to sum * and the result displayed. Operation of adder() is ended by * entering "end", "exit" or "quit"; "end" returns to the level from * which adder() is called, e.g. with: * * for (;;) adder() * * entering "end" would start a new edition with sum = 0; "quit" and * "exit" return to the top level. * * Each response to ? is read as * a string terminated by a newline; the statements and expressions * in this string are compiled and evaluated as in function evaluation; * thus the string may include variables, assignments, functions, etc. * as in: * * 2 + 3 * x = 2 + 3, x^3 * x^2 * local x = 2; while (x < 100) x *= 2; x % 100 * x * exp(2, 1e-5) * sum * print sum^2; * 3; print sum^2; * * (Here the second line creates x as a global variable; the local * variable x in the fourth line has no effect on the global x. In * the last three lines, sum is the sum of numbers already entered, so * the third last line doubles the value of sum. The value returned * by "print sum^2;" is the null value, so the second last line adds * nothing to sum. The last line returns the value 3, i.e. the last * non-null value found for the expressions separated by semicolons, * so sum will be increased by 3 after the "print sum^2;" command * is executed. xxx The terminating semicolon is essential in the * last two lines. A command like eval("print 7;") is acceptable to * calc but eval("print 7") causes an exit from calc. xxx) * * If the value returned is not a number (e.g. the name of a list or matrix, * or if the string has syntax errors as in "2 + ", in which case the * value returned is an error value), the compile error messages and a * request for another number are displayed. * * Calling showvalues(str) assumes str defines a function of x as in: * * "sin(x)", "x^2 + 3*x", "exp(x, 1e-5)". * * Values of the function so defined are returned for values of x * entered in reponse to the ? prompt. Operation is terminated by * entering "end", "exit" or "quit". */ define adder() { global sum = 0; local s, t; for (;;) { s = prompt("? "); if (s == "end") break; t = eval(s); if (!isnum(t)) { print "Please enter a number"; continue; } sum += t; print "\t":sum; } } global prompt_x; define showvalues(str) { local s; for (;;) { s = prompt("? "); if (s == "end") break; prompt_x = eval(s); if (!isnum(prompt_x)) { print "Please enter a number"; continue; } print "\t":eval(str); } }  .Z ..strlennextcandfgets size ordisobjscript freeeulertypes acotatanh statement freebernoullierrcountcontribiroot root avgusertime joinblkcpyarrowerror cothstrscanlfactorisnumisidentishashlibcalcindices argv filesizeoffactorcfappr rcsqisassocfflushpound atanputenvremove xorerrnostrscanfsleepquomod re prevprimestrpos timelowbitsrand taniserror asin popaccess estrbuiltinfloor isdefineddisplayforallNAME strlen - number of characters in a string SYNOPSIS strlen(x) TYPES x string return integer DESCRIPTION strlen(x) returns the number of characters in x EXAMPLE ; print strlen(""), strlen("abc"), strlen("a b\tc\\d") 0 3 7 LIMITS none LINK LIBRARY none SEE ALSO strcat, strcpy, strerror, strncmp, strncpy, strpos, strprintf, strscan, strscanf, substr ## Copyright (C) 1999-2006 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: strlen,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/strlen,v $ ## ## Under source code control: 1995/10/05 04:52:27 ## File existed as early as: 1995 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME nextcand - next candidate for primeness SYNOPSIS nextcand(n [,count [, skip [, residue [,modulus]]]]) TYPES n integer count integer with absolute value less than 2^24, defaults to 1 skip integer. defaults to 1 residue integer, defaults to 0 modulus integer, defaults to 1 return integer DESCRIPTION If modulus is nonzero, nextcand(n, count, skip, residue, modulus) returns the least integer i greater than abs(n) expressible as residue + k * modulus, where k is an integer, for which ptest(i,count,skip) == 1, or if there is no such integer, zero. If abs(n) < 2^32, count >= 0, and the returned value i is not zero, then i is definitely prime. If count is not zero and the returned value i is greater than 2^32, then i is probably prime, particularly if abs(count) > 1. If skip == 0, and abs(n) >= 2^32 or count < 0, the probabilistic test with random bases is used so that if n is composite the probability that it passes ptest() is less than 4^-abs(count). If skip == 1 (the default value), the bases used in the probabilistic test are the first abs(count) primes 2, 3, 5, ... For other values of skip, the bases used in the probabilistic tests are the abs(count) consecutive integers, skip, skip + 1, skip + 2, ... In any case, if the integer returned by nextcand() is not zero, all integers between abs(n) and that integer are composite. If modulus is zero, the value returned is that of residue if this is greater than abs(n) and ptest(residue,count,skip) = 1. Otherwise zero is returned. RUNTIME The runtime for v = nextcand(n, ...) will depend strongly on the number and nature of the integers between n and v. If this number is reasonably large the size of count is largely irrelevant as the compositeness of the numbers between n and v will usually be determined by the test for small prime factors or one pseudoprime test with some base b. If N > 1, count should be positive so that candidates divisible by small primes will be passed over quickly. On the average for random n with large word-count N, the runtime seems to be roughly K/N^3 some constant K. EXAMPLE ; print nextcand(50), nextcand(112140,-2), nextcand(112140,-3) 53 112141 112153 ; print nextcand(100,1,1,1,6), nextcand(100,1,1,-1,6) 103 101 ; print nextcand(100,1,1,2,6), nextcand(100,1,1,303,202) 1 101 ; print nextcand(2e60, 1, 1, 31, 1e30) 2000000000000000000000000000053000000000000000000000000000031 LIMITS none LINK LIBRARY int znextcand(ZVALUE n, long count, long skip, ZVALUE res, ZVALUE mod, ZVALUE *cand) SEE ALSO factor, isprime, lfactor, nextprime, prevcand, prevprime, pfact, pix, ptest ## Copyright (C) 1999-2006 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: nextcand,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/nextcand,v $ ## ## Under source code control: 1996/02/25 00:27:43 ## File existed as early as: 1996 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME fgets - read the next line from a file, newline is kept SYNOPSIS fgets(fd) TYPES fd file return str or nil DESCRIPTION This function reads the next line, including any trailing newline from the open file associated with fd. Unlike fgetline, the trailing newline is included in the return string. If a line is read, it is returned, otherwise (EOF or ERROR) nil is returned. EXAMPLE ; fd = fopen("/tmp/newfile", "w") ; fputs(fd, "chongo was here\n") ; fd2 = fopen("/tmp/newfile", "r") ; fgets(fd2) "chongo was here " ; fclose(fd2) ; fd2 = fopen("/tmp/newfile", "r") ; fgetline(fd2) "chongo was here" LIMITS fd must be associated with an open file LINK LIBRARY none SEE ALSO errno, fclose, feof, ferror, fflush, fgetc, fgetline, fgets, files, fopen, fprintf, fputc, fputs, fseek, fsize, ftell, isfile, printf, prompt ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: fgets,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/fgets,v $ ## ## Under source code control: 1995/03/04 11:33:19 ## File existed as early as: 1995 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME size - number of elements in value SYNOPSIS size(x) TYPES x any return integer DESCRIPTION For the different types of value x may have, size(x) is defined as follows: null 0 real number 1 complex number 1 string length of string (not counding the trailing \0) matrix number of elements list number of members association number of (elements, value) pairs object value returned by xx_size(x) if x of type xx file length of the file in octets rand state 1 random state 1 config state 1 hash state 1 block numer of octets of data it currently holds octet 1 named block numer of octets of data it currently holds EXAMPLE ; print size(null()), size(3), size(2 - 7i), size("abc") 0 1 1 1 ; mat M[2,3] ; print size(M), size(list()), size(list(2,3,4)) 6 0 3 ; A = assoc() ; A[1] = 3, A[1,2] = 6, A["three"] = 5 ; print size(A) 3 ; obj point {x,y} ; obj point P = {4,-5} ; define point_size(a) = abs(a.x) + abs(a.y) ; print size(P) 9 LIMITS none LINK LIBRARY none SEE ALSO list, mat, assoc, obj, sizeof, memsize ## Copyright (C) 1999-2006 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: size,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/size,v $ ## ## Under source code control: 1994/03/19 03:13:22 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME ord - return integer corresponding to character value SYNOPSIS ord(c) TYPES c string return int DESCRIPTION Return the integer value of the first character of a string. EXAMPLE ; print ord("DBell"), ord("chongo"), ord("/\../\"), ord("!") 68 99 47 33 LIMITS none LINK LIBRARY none SEE ALSO char ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: ord,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/ord,v $ ## ## Under source code control: 1994/09/30 01:45:46 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME isobj - whether a value is an object SYNOPSIS isobj(x) TYPES x any, &any return int DESCRIPTION Determine if x is an object. This function will return 1 if x is an object, 0 otherwise. EXAMPLE ; obj surd {a, b} a; ; print isobj(a), isobj(1) 1 0 LIMITS none LINK LIBRARY none SEE ALSO obj, isassoc, isatty, isblk, isconfig, isdefined, iserror, iseven, isfile, ishash, isident, isint, islist, ismat, ismult, isnull, isnum, isobjtype, isodd, isprime, isrand, israndom, isreal, isrel, issimple, issq, isstr, istype ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: isobj,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/isobj,v $ ## ## Under source code control: 1994/10/21 02:21:29 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ Calc shell scripts ------------------ 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. As a simple example, assuming a C or Bourne shell, let add be a file containing just one line: calc -q -- $1 + $2 Then: ./add 1.23 4.56 should respond with the display of: 5.9 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". By making add executable by a command like: chmod u+x add the command used here may be simplified to: ./add 1.23 4.56 Here we shall assume that any script we refer to has been made executable in this way. 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. For example, the add script should have no problem with commands like: ./add "sqrt(2)" "3 * 4" ./add "mat A[2,2] = {1,2,3,4}" "A^2" ./add "2 + 3i" "(3 + 4i)^2" If the shell arguments are to be integers, one could use scripts like the following with arithmetic expansion for the bash and ksh: 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/local/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; IMPORTANT NOTE: The -f flag must be at the very end of the #! line. The #! line must be the first line of the exeuctable file. The path after the #! must be the full path to the calc executable. 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/local/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: help usage help argv help config help cscript ## 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 ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: script,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/script,v $ ## ## Under source code control: 1999/11/30 05:29:48 ## File existed as early as: 1999 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME freeeuler - free stored Euler numbers SYNOPSIS freeeuler() TYPES return none DESCRIPTION The memory used to store calculated Euler numbers is freed by freeeuler(). EXAMPLE ; freeeuler(); LIMITS none LINK LIBRARY void qfreeeuler(void); SEE ALSO euler, bernoulli, freebernoulli ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: freeeuler,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/freeeuler,v $ ## ## Under source code control: 2000/12/14 01:33:00 ## File existed as early as: 2000 ## ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ Builtin types The calculator has the following built-in types. null value This is the undefined value type. The function 'null' returns this value. Functions which do not explicitly return a value return this type. If a function is called with fewer parameters than it is defined for, then the missing parameters have the null type. The null value is false if used in an IF test. rational numbers This is the basic data type of the calculator. These are fractions whose numerators and denominators can be arbitrarily large. The fractions are always in lowest terms. Integers have a denominator of 1. The numerator of the number contains the sign, so that the denominator is always positive. When a number is entered in floating point or exponential notation, it is immediately converted to the appropriate fractional value. Printing a value as a floating point or exponential value involves a conversion from the fractional representation. Numbers are stored in binary format, so that in general, bit tests and shifts are quicker than multiplies and divides. Similarly, entering or displaying of numbers in binary, octal, or hex formats is quicker than in decimal. The sign of a number does not affect the bit representation of a number. complex numbers Complex numbers are composed of real and imaginary parts, which are both fractions as defined above. An integer which is followed by an 'i' character is a pure imaginary number. Complex numbers such as "2+3i" when typed in, are processed as the sum of a real and pure imaginary number, resulting in the desired complex number. Therefore, parenthesis are sometimes necessary to avoid confusion, as in the two values: 1+2i ^2 (which is -3) (1+2i) ^2 (which is -3+4i) Similar care is required when entering fractional complex numbers. Note the differences below: 3/4i (which is -(3/4)i) 3i/4 (which is (3/4)i) The imaginary unit itself is input using "1i". strings Strings are a sequence of zero or more characters. They are input using either of the single or double quote characters. The quote mark which starts the string also ends it. Various special characters can also be inserted using back-slash. Example strings: "hello\n" "that's all" 'lots of """"' 'a' "" There is no distinction between single character and multi-character strings. The 'str' and 'ord' functions will convert between a single character string and its numeric value. The 'str' and 'eval' functions will convert between longer strings and the corresponding numeric value (if legal). The 'strcat', 'strlen', and 'substr' functions are also useful. matrices These are one to four dimensional matrices, whose minimum and maximum bounds can be specified at runtime. Unlike C, the minimum bounds of a matrix do not have to start at 0. The elements of a matrix can be of any type. There are several built-in functions for matrices. Matrices are created using the 'mat' statement. associations These are one to four dimensional matrices which can be indexed by arbitrary values, instead of just integers. These are also known as associative arrays. The elements of an association can be of any type. Very few operations are permitted on an association except for indexing. Associations are created using the 'assoc' function. lists These are a sequence of values, which are linked together so that elements can be easily be inserted or removed anywhere in the list. The values can be of any type. Lists are created using the 'list' function. files These are text files opened using stdio. Files may be opened for sequential reading, writing, or appending. Opening a file using the 'fopen' function returns a value which can then be used to perform I/O to that file. File values can be copied by normal assignments between variables, or by using the result of the 'files' function. Such copies are indistinguishable from each other. ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: types,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/types,v $ ## ## Under source code control: 1991/07/21 04:37:24 ## File existed as early as: 1991 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME acot - inverse trigonometric cotangent SYNOPSIS acot(x [,eps]) TYPES x real eps nonzero real, defaults to epsilon() return real DESCRIPTION Returns the acot of x to a multiple of eps with error less in absolute value than .75 * eps. v = acot(x) is the number in (0, pi) for which cot(v) = x. EXAMPLE ; print acot(2, 1e-5), acot(2, 1e-10), acot(2, 1e-15), acot(2, 1e-20) .46365 .463647609 .463647609000806 .46364760900080611621 LIMITS none LINK LIBRARY NUMBER *qacot(NUMBER *x, NUMBER *eps) SEE ALSO asin, acos, atan, asec, acsc, epsilon ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: acot,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/acot,v $ ## ## Under source code control: 1995/11/13 03:49:00 ## File existed as early as: 1995 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ NAME atanh - inverse hyperbolic tangent SYNOPSIS atanh(x [,eps]) TYPES x real eps nonzero real, defaults to epsilon() return real DESCRIPTION Returns the atanh of x to a multiple of eps with error less in absolute value than .75 * eps. atanh(x) is the real number v for which tanh(v) = x. It is given by atanh(x) = ln((1 + x)/(1 - x))/2 EXAMPLE ; print atanh(.5,1e-5), atanh(.5,1e-10), atanh(.5,1e-15), atanh(.5,1e-20) .54931 .5493061443 .549306144334055 .5493061443340548457 LIMITS none LINK LIBRARY NUMBER *qatanh(NUMBER *x, NUMBER *eps) SEE ALSO asinh, acosh, asech, acsch, acoth, epsilon ## Copyright (C) 1999 Landon Curt Noll ## ## 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. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## ## @(#) $Revision: 30.1 $ ## @(#) $Id: atanh,v 30.1 2007/03/16 11:10:42 chongo Exp $ ## @(#) $Source: /usr/local/src/cmd/calc/help/RCS/atanh,v $ ## ## Under source code control: 1994/03/19 01:40:27 ## File existed as early as: 1994 ## ## chongo /\oo/\ http://www.isthe.com/chongo/ ## Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ Statements Statements are very much like C statements. Most statements act identically to those in C, but there are minor differences and some additions. The following is a list of the statement types, with explanation of the non-C statements. Statements are generally terminated with semicolons or { ... }. C-like statements ----------------- { statement } { statement; ... statement } C-like flow control ------------------- if (expr) statement if (expr) statement else statement for (optionalexpr ; optionalexpr ; optionalexpr) statement while (expr) statement do statement while (expr) These all work like in normal C. IMPORTANT NOTE: When statement is of the form { ... }, the leading { must be on the same line as the if, for, while or do keyword. This works as expected: if (expr) { ... } However this WILL NOT WORK AS EXPECTED: if (expr) { ... } because calc will parse the if being terminated by an empty statement followed by a if (expr) ; { ... } In the same way, use these forms: for (optionalexpr ; optionalexpr ; optionalexpr) { ... } while (expr) { ... } do { ... while (expr); where the initial { is on the SAME LINE as the if, while, for or do. See 'help expression' for details on expressions. See 'help builtin' for details on calc builtin functions. See 'help unexpanded' for things C programmers do not expect. See also 'help todo' and 'help bugs'. C-like flow breaks ------------------ continue break goto label These all work like in normal C. See 'help expression' for details on expressions. See 'help builtin' for details on calc builtin functions. return ------ return return expr return ( expr ) This returns a value from a function. Functions always have a return value, even if this statement is not used. If no return statement is executed, or if no expression is specified in the return statement, then the return value from the function is the null type. switch ------ switch (expr) { caseclauses } Switch statements work similarly to C, except for the following. A switch can be done on any type of value, and the case statements can be of any type of values. The case statements can also be expressions calculated at runtime. The calculator compares the switch value with each case statement in the order specified, and selects the first case which matches. The default case is the exception, and only matches once all other cases have been tested. matrix ------ mat variable [dimension] [dimension] ... mat variable [dimension, dimension, ...] mat variable [] = { value, ... } This creates a matrix variable with the specified dimensions. Matrices can have from 1 to 4 dimensions. When specifying multiple dimensions, you can use either the standard C syntax, or else you can use commas for separating the dimensions. For example, the following two statements are equivalent, and so will create the same two dimensional matrix: mat foo[3][6]; mat foo[3,6]; By default, each dimension is indexed starting at zero, as in normal C, and contains the specified number of elements. However, this can be changed if a colon is used to separate two values. If this is done, then the two values become the lower and upper bounds for indexing. This is convenient, for example, to create matrices whose first row and column begin at 1. Examples of matrix definitions are: mat x[3] one dimension, bounds are 0-2 mat foo[4][5] two dimensions, bounds are 0-3 and 0-4 mat a[-7:7] one dimension, bounds are (-7)-7 mat s[1:9,1:9] two dimensions, bounds are 1-9 and 1-9 Note that the MAT statement is not a declaration, but is executed at runtime. Within a f