home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / compsrcs / unix / volume26 / calc / part10 < prev    next >
Encoding:
Text File  |  1992-05-09  |  53.6 KB  |  2,519 lines

  1. Newsgroups: comp.sources.unix
  2. From: dbell@pdact.pd.necisa.oz.au (David I. Bell)
  3. Subject: v26i036: CALC - An arbitrary precision C-like calculator, Part10/21
  4. Sender: unix-sources-moderator@pa.dec.com
  5. Approved: vixie@pa.dec.com
  6.  
  7. Submitted-By: dbell@pdact.pd.necisa.oz.au (David I. Bell)
  8. Posting-Number: Volume 26, Issue 36
  9. Archive-Name: calc/part10
  10.  
  11. #! /bin/sh
  12. # This is a shell archive.  Remove anything before this line, then unpack
  13. # it by saving it into a file and typing "sh file".  To overwrite existing
  14. # files, type "sh file -c".  You can also feed this as standard input via
  15. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  16. # will see the following message at the end:
  17. #        "End of archive 10 (of 21)."
  18. # Contents:  io.c qfunc.c
  19. # Wrapped by dbell@elm on Tue Feb 25 15:21:08 1992
  20. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  21. if test -f 'io.c' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'io.c'\"
  23. else
  24. echo shar: Extracting \"'io.c'\" \(26180 characters\)
  25. sed "s/^X//" >'io.c' <<'END_OF_FILE'
  26. X/*
  27. X * Copyright (c) 1992 David I. Bell
  28. X * Permission is granted to use, distribute, or modify this source,
  29. X * provided that this copyright notice remains intact.
  30. X *
  31. X * Scanf and printf routines for extended precision numbers
  32. X */
  33. X
  34. X#include <stdio.h>
  35. X#include "stdarg.h"
  36. X#include "math.h"
  37. X
  38. X#define    OUTBUFSIZE    200        /* realloc size for output buffers */
  39. X
  40. X
  41. X#define    PUTCHAR(ch)        math_chr(ch)
  42. X#define    PUTSTR(str)        math_str(str)
  43. X#define    PRINTF1(fmt, a1)    math_fmt(fmt, a1)
  44. X#define    PRINTF2(fmt, a1, a2)    math_fmt(fmt, a1, a2)
  45. X
  46. X
  47. Xlong    _outdigits_ = 20;        /* default digits for output */
  48. Xint    _outmode_ = MODE_INITIAL;    /* default output mode */
  49. X
  50. X
  51. X/*
  52. X * Output state that has been saved when diversions are done.
  53. X */
  54. Xtypedef struct iostate IOSTATE;
  55. Xstruct iostate {
  56. X    IOSTATE *oldiostates;        /* previous saved state */
  57. X    long outdigits;            /* digits for output */
  58. X    int outmode;            /* output mode */
  59. X    FILE *outfp;            /* file unit for output (if any) */
  60. X    char *outbuf;            /* output string buffer (if any) */
  61. X    long outbufsize;        /* current size of string buffer */
  62. X    long outbufused;        /* space used in string buffer */
  63. X    BOOL outputisstring;        /* TRUE if output is to string buffer */
  64. X};
  65. X
  66. X
  67. Xstatic IOSTATE    *oldiostates = NULL;    /* list of saved output states */
  68. Xstatic FILE    *outfp = stdout;    /* file unit for output */
  69. Xstatic char    *outbuf = NULL;        /* current diverted buffer */
  70. Xstatic long    scalefactor;
  71. Xstatic long    outbufsize;
  72. Xstatic long    outbufused;
  73. Xstatic BOOL    outputisstring;
  74. Xstatic ZVALUE    scalenumber = { 0, 0, 0 };
  75. X
  76. X#if 0
  77. Xstatic long    etoalen;
  78. Xstatic char    *etoabuf = NULL;
  79. X#endif
  80. X
  81. Xstatic void zprintx proto((ZVALUE z, long width));
  82. Xstatic void zprintb proto((ZVALUE z, long width));
  83. Xstatic void zprinto proto((ZVALUE z, long width));
  84. Xstatic void zprintval proto((ZVALUE z, long decimals, long width));
  85. X
  86. Xstatic void atoz proto((char * s, ZVALUE * res));
  87. X
  88. Xstatic void qprintff();
  89. Xstatic void qprintfd();
  90. Xstatic void qprintfe();
  91. Xstatic void qprintfr();
  92. Xstatic void qprintfo();
  93. Xstatic void qprintfb();
  94. X#ifdef CODE
  95. Xextern void qprintfx();
  96. X#else
  97. Xstatic void qprintfx();
  98. X#endif
  99. X
  100. X
  101. X/*
  102. X * Routine to output a character either to a FILE
  103. X * handle or into a string.
  104. X */
  105. Xvoid
  106. Xmath_chr(ch)
  107. X{
  108. X    char    *cp;
  109. X
  110. X    if (!outputisstring) {
  111. X        fputc(ch, outfp);
  112. X        return;
  113. X    }
  114. X    if (outbufused >= outbufsize) {
  115. X        cp = (char *)realloc(outbuf, outbufsize + OUTBUFSIZE + 1);
  116. X        if (cp == NULL)
  117. X            error("Cannot realloc output string");
  118. X        outbuf = cp;
  119. X        outbufsize += OUTBUFSIZE;
  120. X    }
  121. X    outbuf[outbufused++] = (char)ch;
  122. X}
  123. X
  124. X
  125. X/*
  126. X * Routine to output a null-terminated string either
  127. X * to a FILE handle or into a string.
  128. X */
  129. Xvoid
  130. Xmath_str(str)
  131. X    char    *str;
  132. X{
  133. X    char    *cp;
  134. X    int    len;
  135. X
  136. X    if (!outputisstring) {
  137. X        fputs(str, outfp);
  138. X        return;
  139. X    }
  140. X    len = strlen(str);
  141. X    if ((outbufused + len) > outbufsize) {
  142. X        cp = (char *)realloc(outbuf, outbufsize + len + OUTBUFSIZE + 1);
  143. X        if (cp == NULL)
  144. X            error("Cannot realloc output string");
  145. X        outbuf = cp;
  146. X        outbufsize += (len + OUTBUFSIZE);
  147. X    }
  148. X    memcpy(&outbuf[outbufused], str, len);
  149. X    outbufused += len;
  150. X}
  151. X
  152. X
  153. X/*
  154. X * Routine to output a printf-style formatted string either
  155. X * to a FILE handle or into a string.
  156. X */
  157. X#ifdef VARARGS
  158. X# define VA_ALIST fmt, va_alist
  159. X# define VA_DCL char *fmt; va_dcl
  160. X#else
  161. X# ifdef __STDC__
  162. X#  define VA_ALIST char *fmt, ...
  163. X#  define VA_DCL
  164. X# else
  165. X#  define VA_ALIST fmt
  166. X#  define VA_DCL char *fmt;
  167. X# endif
  168. X#endif
  169. X/*VARARGS*/
  170. Xvoid
  171. Xmath_fmt(VA_ALIST)
  172. X    VA_DCL
  173. X{
  174. X    va_list ap;
  175. X    char buf[200];
  176. X
  177. X#ifdef VARARGS
  178. X    va_start(ap);
  179. X#else
  180. X    va_start(ap, fmt);
  181. X#endif
  182. X    vsprintf(buf, fmt, ap);
  183. X    va_end(ap);
  184. X    math_str(buf);
  185. X}
  186. X
  187. X
  188. X/*
  189. X * Flush the current output stream.
  190. X */
  191. Xvoid
  192. Xmath_flush()
  193. X{
  194. X    if (!outputisstring)
  195. X        fflush(outfp);
  196. X}
  197. X
  198. X
  199. X/*
  200. X * Divert further output so that it is saved into a string that will be
  201. X * returned later when the diversion is completed.  The current state of
  202. X * output is remembered for later restoration.  Diversions can be nested.
  203. X * Output diversion is only intended for saving output to "stdout".
  204. X */
  205. Xvoid
  206. Xdivertio()
  207. X{
  208. X    register IOSTATE *sp;
  209. X
  210. X    sp = (IOSTATE *) malloc(sizeof(IOSTATE));
  211. X    if (sp == NULL)
  212. X        error("No memory for diverting output");
  213. X    sp->oldiostates = oldiostates;
  214. X    sp->outdigits = _outdigits_;
  215. X    sp->outmode = _outmode_;
  216. X    sp->outfp = outfp;
  217. X    sp->outbuf = outbuf;
  218. X    sp->outbufsize = outbufsize;
  219. X    sp->outbufused = outbufused;
  220. X    sp->outputisstring = outputisstring;
  221. X
  222. X    outbufused = 0;
  223. X    outbufsize = 0;
  224. X    outbuf = (char *) malloc(OUTBUFSIZE + 1);
  225. X    if (outbuf == NULL)
  226. X        error("Cannot allocate divert string");
  227. X    outbufsize = OUTBUFSIZE;
  228. X    outputisstring = TRUE;
  229. X    oldiostates = sp;
  230. X}
  231. X
  232. X
  233. X/*
  234. X * Undivert output and return the saved output as a string.  This also
  235. X * restores the output state to what it was before the diversion began.
  236. X * The string needs freeing by the caller when it is no longer needed.
  237. X */
  238. Xchar *
  239. Xgetdivertedio()
  240. X{
  241. X    register IOSTATE *sp;
  242. X    char *cp;
  243. X
  244. X    sp = oldiostates;
  245. X    if (sp == NULL)
  246. X        error("No diverted state to restore");
  247. X    cp = outbuf;
  248. X    cp[outbufused] = '\0';
  249. X    oldiostates = sp->oldiostates;
  250. X    _outdigits_ = sp->outdigits;
  251. X    _outmode_ = sp->outmode;
  252. X    outfp = sp->outfp;
  253. X    outbuf = sp->outbuf;
  254. X    outbufsize = sp->outbufsize;
  255. X    outbufused = sp->outbufused;
  256. X    outbuf = sp->outbuf;
  257. X    outputisstring = sp->outputisstring;
  258. X    return cp;
  259. X}
  260. X
  261. X
  262. X/*
  263. X * Clear all diversions and set output back to the original destination.
  264. X * This is called when resetting the global state of the program.
  265. X */
  266. Xvoid
  267. Xcleardiversions()
  268. X{
  269. X    while (oldiostates)
  270. X        free(getdivertedio());
  271. X}
  272. X
  273. X
  274. X/*
  275. X * Set the output routines to output to the specified FILE stream.
  276. X * This interacts with output diversion in the following manner.
  277. X *    STDOUT    diversion    action
  278. X *    ----    ---------    ------
  279. X *    yes    yes        set output to diversion string again.
  280. X *    yes    no        set output to stdout.
  281. X *    no    yes        set output to specified file.
  282. X *    no    no        set output to specified file.
  283. X */
  284. Xvoid
  285. Xsetfp(newfp)
  286. X    FILE *newfp;
  287. X{
  288. X    outfp = newfp;
  289. X    outputisstring = (oldiostates && (newfp == stdout));
  290. X}
  291. X
  292. X
  293. X/*
  294. X * Set the output mode for numeric output.
  295. X */
  296. Xvoid
  297. Xsetmode(newmode)
  298. X{
  299. X    if ((newmode <= MODE_DEFAULT) || (newmode > MODE_MAX))
  300. X        error("Setting illegal output mode");
  301. X    _outmode_ = newmode;
  302. X}
  303. X
  304. X
  305. X/*
  306. X * Set the number of digits for float or exponential output.
  307. X */
  308. Xvoid
  309. Xsetdigits(newdigits)
  310. X    long newdigits;
  311. X{
  312. X    if (newdigits < 0)
  313. X        error("Setting illegal number of digits");
  314. X    _outdigits_ = newdigits;
  315. X}
  316. X
  317. X
  318. X/*
  319. X * Print a formatted string containing arbitrary numbers, similar to printf.
  320. X * ALL numeric arguments to this routine are rational NUMBERs.
  321. X * Various forms of printing such numbers are supplied, in addition
  322. X * to strings and characters.  Output can actually be to any FILE
  323. X * stream or a string.
  324. X */
  325. X#ifdef VARARGS
  326. X# define VA_ALIST1 fmt, va_alist
  327. X# define VA_DCL1 char *fmt; va_dcl
  328. X#else
  329. X# ifdef __STDC__
  330. X#  define VA_ALIST1 char *fmt, ...
  331. X#  define VA_DCL1
  332. X# else
  333. X#  define VA_ALIST1 fmt
  334. X#  define VA_DCL1 char *fmt;
  335. X# endif
  336. X#endif
  337. X/*VARARGS*/
  338. Xvoid
  339. Xqprintf(VA_ALIST1)
  340. X    VA_DCL1
  341. X{
  342. X    va_list ap;
  343. X    NUMBER *q;
  344. X    int ch, sign;
  345. X    long width, precision;
  346. X
  347. X#ifdef VARARGS
  348. X    va_start(ap);
  349. X#else
  350. X    va_start(ap, fmt);
  351. X#endif
  352. X    while ((ch = *fmt++) != '\0') {
  353. X        if (ch == '\\') {
  354. X            ch = *fmt++;
  355. X            switch (ch) {
  356. X                case 'n': ch = '\n'; break;
  357. X                case 'r': ch = '\r'; break;
  358. X                case 't': ch = '\t'; break;
  359. X                case 'f': ch = '\f'; break;
  360. X                case 'v': ch = '\v'; break;
  361. X                case 'b': ch = '\b'; break;
  362. X                case 0:
  363. X                    va_end(ap);
  364. X                    return;
  365. X            }
  366. X            PUTCHAR(ch);
  367. X            continue;
  368. X        }
  369. X        if (ch != '%') {
  370. X            PUTCHAR(ch);
  371. X            continue;
  372. X        }
  373. X        ch = *fmt++;
  374. X        width = 0; precision = 8; sign = 1;
  375. Xpercent:    ;
  376. X        switch (ch) {
  377. X            case 'd':
  378. X                q = va_arg(ap, NUMBER *);
  379. X                qprintfd(q, width);
  380. X                break;
  381. X            case 'f':
  382. X                q = va_arg(ap, NUMBER *);
  383. X                qprintff(q, width, precision);
  384. X                break;
  385. X            case 'e':
  386. X                q = va_arg(ap, NUMBER *);
  387. X                qprintfe(q, width, precision);
  388. X                break;
  389. X            case 'r':
  390. X            case 'R':
  391. X                q = va_arg(ap, NUMBER *);
  392. X                qprintfr(q, width, (BOOL) (ch == 'R'));
  393. X                break;
  394. X            case 'N':
  395. X                q = va_arg(ap, NUMBER *);
  396. X                zprintval(q->num, 0L, width);
  397. X                break;
  398. X            case 'D':
  399. X                q = va_arg(ap, NUMBER *);
  400. X                zprintval(q->den, 0L, width);
  401. X                break;
  402. X            case 'o':
  403. X                q = va_arg(ap, NUMBER *);
  404. X                qprintfo(q, width);
  405. X                break;
  406. X            case 'x':
  407. X                q = va_arg(ap, NUMBER *);
  408. X                qprintfx(q, width);
  409. X                break;
  410. X            case 'b':
  411. X                q = va_arg(ap, NUMBER *);
  412. X                qprintfb(q, width);
  413. X                break;
  414. X            case 's':
  415. X                PUTSTR(va_arg(ap, char *));
  416. X                break;
  417. X            case 'c':
  418. X                PUTCHAR(va_arg(ap, int));
  419. X                break;
  420. X            case 0:
  421. X                va_end(ap);
  422. X                return;
  423. X            case '-':
  424. X                sign = -1;
  425. X                ch = *fmt++;
  426. X            default:
  427. X        if (('0' <= ch && ch <= '9') || ch == '.' || ch == '*') {
  428. X            if (ch == '*') {
  429. X                q = va_arg(ap, NUMBER *);
  430. X                width = sign * qtoi(q);
  431. X                ch = *fmt++;
  432. X            } else if (ch != '.') {
  433. X                width = ch - '0';
  434. X                while ('0' <= (ch = *fmt++) && ch <= '9')
  435. X                    width = width * 10 + ch - '0';
  436. X                width *= sign;
  437. X            }
  438. X            if (ch == '.') {
  439. X                if ((ch = *fmt++) == '*') {
  440. X                    q = va_arg(ap, NUMBER *);
  441. X                    precision = qtoi(q);
  442. X                    ch = *fmt++;
  443. X                } else {
  444. X                    precision = 0;
  445. X                    while ('0' <= (ch = *fmt++) && ch <= '9')
  446. X                        precision = precision * 10 + ch - '0';
  447. X                }
  448. X            }
  449. X            goto percent;
  450. X        }
  451. X        }
  452. X    }
  453. X    va_end(ap);
  454. X}
  455. X
  456. X
  457. X#if 0
  458. X/*
  459. X * Read a number from the specified FILE stream (NULL means stdin).
  460. X * The number can be an integer, a fraction, a real number, an
  461. X * exponential number, or a hex, octal or binary number.  Leading blanks
  462. X * are skipped.  Illegal numbers return NULL.  Unrecognized characters
  463. X * remain to be read on the line.
  464. X *    q = qreadval(fp);
  465. X */
  466. XNUMBER *
  467. Xqreadval(fp)
  468. X    FILE *fp;        /* file stream to read from (or NULL) */
  469. X{
  470. X    NUMBER *r;        /* returned number */
  471. X    char *cp;         /* current buffer location */
  472. X    long savecc;        /* characters saved in buffer */
  473. X    long scancc;         /* characters parsed correctly */
  474. X    int ch;            /* current character */
  475. X
  476. X    if (fp == NULL)
  477. X        fp = stdin;
  478. X    if (etoabuf == NULL) {
  479. X        etoabuf = (char *)malloc(OUTBUFSIZE + 2);
  480. X        if (etoabuf == NULL)
  481. X            return NULL;
  482. X        etoalen = OUTBUFSIZE;
  483. X    }
  484. X    cp = etoabuf;
  485. X    ch = fgetc(fp);
  486. X    while ((ch == ' ') || (ch == '\t'))
  487. X        ch = fgetc(fp);
  488. X    savecc = 0;
  489. X    for (;;) {
  490. X        if (ch == EOF)
  491. X            return NULL;
  492. X        if (savecc >= etoalen)
  493. X        {
  494. X            cp = (char *)realloc(etoabuf, etoalen + OUTBUFSIZE + 2);
  495. X            if (cp == NULL)
  496. X                return NULL;
  497. X            etoabuf = cp;
  498. X            etoalen += OUTBUFSIZE;
  499. X            cp += savecc;
  500. X        }
  501. X        *cp++ = (char)ch;
  502. X        *cp = '\0';
  503. X        scancc = qparse(etoabuf, QPF_SLASH);
  504. X        if (scancc != ++savecc)
  505. X            break;
  506. X        ch = fgetc(fp);
  507. X    }
  508. X    ungetc(ch, fp);
  509. X    if (scancc < 0)
  510. X        return NULL;
  511. X    r = atoq(etoabuf);
  512. X    if (iszero(r->den)) {
  513. X        qfree(r);
  514. X        r = NULL;
  515. X    }
  516. X    return r;
  517. X}
  518. X#endif
  519. X
  520. X
  521. X/*
  522. X * Print a complex number in rational representation.
  523. X * Example:  2/3-4i/5
  524. X */
  525. Xvoid
  526. Xcprintfr(c)
  527. X    COMPLEX *c;
  528. X{
  529. X    NUMBER *r;
  530. X    NUMBER *i;
  531. X
  532. X    r = c->real;
  533. X    i = c->imag;
  534. X    if (!qiszero(r) || qiszero(i))
  535. X        qprintfr(r, 0L, FALSE);
  536. X    if (qiszero(i))
  537. X        return;
  538. X    if (!qiszero(r) && !qisneg(i))
  539. X        PUTCHAR('+');
  540. X    zprintval(i->num, 0L, 0L);
  541. X    PUTCHAR('i');
  542. X    if (qisfrac(i)) {
  543. X        PUTCHAR('/');
  544. X        zprintval(i->den, 0L, 0L);
  545. X    }
  546. X}
  547. X
  548. X
  549. X/*
  550. X * Print a number in the specified output mode.
  551. X * If MODE_DEFAULT is given, then the default output mode is used.
  552. X * Any approximate output is flagged with a leading tilde.
  553. X * Integers are always printed as themselves.
  554. X */
  555. Xvoid
  556. Xqprintnum(q, outmode)
  557. X    NUMBER *q;
  558. X{
  559. X    NUMBER tmpval;
  560. X    long prec, exp;
  561. X
  562. X    if (outmode == MODE_DEFAULT)
  563. X        outmode = _outmode_;
  564. X    if ((outmode == MODE_FRAC) || ((outmode == MODE_REAL) && qisint(q))) {
  565. X        qprintfr(q, 0L, FALSE);
  566. X        return;
  567. X    }
  568. X    switch (outmode) {
  569. X        case MODE_INT:
  570. X            if (qisfrac(q))
  571. X                PUTCHAR('~');
  572. X            qprintfd(q, 0L);
  573. X            break;
  574. X
  575. X        case MODE_REAL:
  576. X            prec = qplaces(q);
  577. X            if ((prec < 0) || (prec > _outdigits_)) {
  578. X                prec = _outdigits_;
  579. X                PUTCHAR('~');
  580. X            }
  581. X            qprintff(q, 0L, prec);
  582. X            break;
  583. X
  584. X        case MODE_EXP:
  585. X            if (qiszero(q)) {
  586. X                PUTCHAR('0');
  587. X                return;
  588. X            }
  589. X            tmpval = *q;
  590. X            tmpval.num.sign = 0;
  591. X            exp = qilog10(&tmpval);
  592. X            if (exp == 0) {        /* in range to output as real */
  593. X                qprintnum(q, MODE_REAL);
  594. X                return;
  595. X            }
  596. X            tmpval.num = _one_;
  597. X            tmpval.den = _one_;
  598. X            if (exp > 0)
  599. X                ztenpow(exp, &tmpval.den);
  600. X            else
  601. X                ztenpow(-exp, &tmpval.num);
  602. X            q = qmul(q, &tmpval);
  603. X            freeh(tmpval.num.v);
  604. X            freeh(tmpval.den.v);
  605. X            qprintnum(q, MODE_REAL);
  606. X            qfree(q);
  607. X            PRINTF1("e%ld", exp);
  608. X            break;
  609. X
  610. X        case MODE_HEX:
  611. X            qprintfx(q, 0L);
  612. X            break;
  613. X
  614. X        case MODE_OCTAL:
  615. X            qprintfo(q, 0L);
  616. X            break;
  617. X
  618. X        case MODE_BINARY:
  619. X            qprintfb(q, 0L);
  620. X            break;
  621. X
  622. X        default:
  623. X            error("Bad mode for print");
  624. X    }
  625. X}
  626. X
  627. X
  628. X/*
  629. X * Print a number in floating point representation.
  630. X * Example:  193.784
  631. X */
  632. Xstatic void
  633. Xqprintff(q, width, precision)
  634. X    NUMBER *q;
  635. X    long width;
  636. X    long precision;
  637. X{
  638. X    ZVALUE z, z1;
  639. X
  640. X    if (precision != scalefactor) {
  641. X        if (scalenumber.v)
  642. X            freeh(scalenumber.v);
  643. X        ztenpow(precision, &scalenumber);
  644. X        scalefactor = precision;
  645. X    }
  646. X    if (scalenumber.v)
  647. X        zmul(q->num, scalenumber, &z);
  648. X    else
  649. X        z = q->num;
  650. X    if (qisfrac(q)) {
  651. X        zquo(z, q->den, &z1);
  652. X        if (z.v != q->num.v)
  653. X            freeh(z.v);
  654. X        z = z1;
  655. X    }
  656. X    if (qisneg(q) && iszero(z))
  657. X        PUTCHAR('-');
  658. X    zprintval(z, precision, width);
  659. X    if (z.v != q->num.v)
  660. X        freeh(z.v);
  661. X}
  662. X
  663. X
  664. X/*
  665. X * Print a number in exponential notation.
  666. X * Example: 4.1856e34
  667. X */
  668. X/*ARGSUSED*/
  669. Xstatic void
  670. Xqprintfe(q, width, precision)
  671. X    register NUMBER *q;
  672. X    long width;
  673. X    long precision;
  674. X{
  675. X    long exponent;
  676. X    NUMBER q2;
  677. X    ZVALUE num, den, tenpow, tmp;
  678. X
  679. X    if (qiszero(q)) {
  680. X        PUTSTR("0.0");
  681. X        return;
  682. X    }
  683. X    num = q->num;
  684. X    den = q->den;
  685. X    num.sign = 0;
  686. X    exponent = zdigits(num) - zdigits(den);
  687. X    if (exponent > 0) {
  688. X        ztenpow(exponent, &tenpow);
  689. X        zmul(den, tenpow, &tmp);
  690. X        freeh(tenpow.v);
  691. X        den = tmp;
  692. X    }
  693. X    if (exponent < 0) {
  694. X        ztenpow(-exponent, &tenpow);
  695. X        zmul(num, tenpow, &tmp);
  696. X        freeh(tenpow.v);
  697. X        num = tmp;
  698. X    }
  699. X    if (zrel(num, den) < 0) {
  700. X        zmuli(num, 10L, &tmp);
  701. X        if (num.v != q->num.v)
  702. X            freeh(num.v);
  703. X        num = tmp;
  704. X        exponent--;
  705. X    }
  706. X    q2.num = num;
  707. X    q2.den = den;
  708. X    q2.num.sign = q->num.sign;
  709. X    qprintff(&q2, 0L, precision);
  710. X    if (exponent)
  711. X        PRINTF1("e%ld", exponent);
  712. X    if (num.v != q->num.v)
  713. X        freeh(num.v);
  714. X    if (den.v != q->den.v)
  715. X        freeh(den.v);
  716. X}
  717. X
  718. X
  719. X/*
  720. X * Print a number in rational representation.
  721. X * Example: 397/37
  722. X */
  723. Xstatic void
  724. Xqprintfr(q, width, force)
  725. X    NUMBER *q;
  726. X    long width;
  727. X    BOOL force;
  728. X{
  729. X    zprintval(q->num, 0L, width);
  730. X    if (force || qisfrac(q)) {
  731. X        PUTCHAR('/');
  732. X        zprintval(q->den, 0L, width);
  733. X    }
  734. X}
  735. X
  736. X
  737. X/*
  738. X * Print a number as an integer (truncating fractional part).
  739. X * Example: 958421
  740. X */
  741. Xstatic void
  742. Xqprintfd(q, width)
  743. X    NUMBER *q;
  744. X    long width;
  745. X{
  746. X    ZVALUE z;
  747. X
  748. X    if (qisfrac(q)) {
  749. X        zquo(q->num, q->den, &z);
  750. X        zprintval(z, 0L, width);
  751. X        freeh(z.v);
  752. X    } else
  753. X        zprintval(q->num, 0L, width);
  754. X}
  755. X
  756. X
  757. X/*
  758. X * Print a number in hex.
  759. X * This prints the numerator and denominator in hex.
  760. X */
  761. X#ifndef CODE
  762. Xstatic 
  763. X#endif
  764. Xvoid
  765. Xqprintfx(q, width)
  766. X    NUMBER *q;
  767. X    long width;
  768. X{
  769. X    zprintx(q->num, width);
  770. X    if (qisfrac(q)) {
  771. X        PUTCHAR('/');
  772. X        zprintx(q->den, 0L);
  773. X    }
  774. X}
  775. X
  776. X
  777. X/*
  778. X * Print a number in binary.
  779. X * This prints the numerator and denominator in binary.
  780. X */
  781. Xstatic void
  782. Xqprintfb(q, width)
  783. X    NUMBER *q;
  784. X    long width;
  785. X{
  786. X    zprintb(q->num, width);
  787. X    if (qisfrac(q)) {
  788. X        PUTCHAR('/');
  789. X        zprintb(q->den, 0L);
  790. X    }
  791. X}
  792. X
  793. X
  794. X/*
  795. X * Print a number in octal.
  796. X * This prints the numerator and denominator in octal.
  797. X */
  798. Xstatic void
  799. Xqprintfo(q, width)
  800. X    NUMBER *q;
  801. X    long width;
  802. X{
  803. X    zprinto(q->num, width);
  804. X    if (qisfrac(q)) {
  805. X        PUTCHAR('/');
  806. X        zprinto(q->den, 0L);
  807. X    }
  808. X}
  809. X
  810. X
  811. X/*
  812. X * Print an integer value as a hex number.
  813. X * The special characters 0x appear to indicate the number is hex.
  814. X */
  815. X/*ARGSUSED*/
  816. Xstatic void
  817. Xzprintx(z, width)
  818. X    ZVALUE z;
  819. X    long width;
  820. X{
  821. X    register HALF *hp;    /* current word to print */
  822. X    int len;        /* number of halfwords to type */
  823. X
  824. X    len = z.len - 1;
  825. X    if (isneg(z))
  826. X        PUTCHAR('-');
  827. X    if ((len == 0) && (*z.v <= (FULL) 9)) {
  828. X        len = '0' + *z.v;
  829. X        PUTCHAR(len);
  830. X        return;
  831. X    }
  832. X    hp = z.v + len;
  833. X    PRINTF1("0x%x", (FULL) *hp--);
  834. X    while (--len >= 0)
  835. X        PRINTF1("%04x", (FULL) *hp--);
  836. X}
  837. X
  838. X
  839. X/*
  840. X * Print an integer value as a binary number.
  841. X * The special characters 0b appear to indicate the number is binary.
  842. X */
  843. X/*ARGSUSED*/
  844. Xstatic void
  845. Xzprintb(z, width)
  846. X    ZVALUE z;
  847. X    long width;
  848. X{
  849. X    register HALF *hp;    /* current word to print */
  850. X    int len;        /* number of halfwords to type */
  851. X    HALF val;        /* current value */
  852. X    HALF mask;        /* current mask */
  853. X    int didprint;        /* nonzero if printed some digits */
  854. X    int ch;            /* current char */
  855. X
  856. X    len = z.len - 1;
  857. X    if (isneg(z))
  858. X        PUTCHAR('-');
  859. X    if ((len == 0) && (*z.v <= (FULL) 1)) {
  860. X        len = '0' + *z.v;
  861. X        PUTCHAR(len);
  862. X        return;
  863. X    }
  864. X    hp = z.v + len;
  865. X    didprint = 0;
  866. X    PUTSTR("0b");
  867. X    while (len-- >= 0) {
  868. X        val = *hp--;
  869. X        mask = (1 << (BASEB - 1));
  870. X        while (mask) {
  871. X            ch = '0' + ((mask & val) != 0);
  872. X            if (didprint || (ch != '0')) {
  873. X                PUTCHAR(ch);
  874. X                didprint = 1;
  875. X            }
  876. X            mask >>= 1;
  877. X        }
  878. X    }
  879. X}
  880. X
  881. X
  882. X/*
  883. X * Print an integer value as an octal number.
  884. X * The number begins with a leading 0 to indicate that it is octal.
  885. X */
  886. X/*ARGSUSED*/
  887. Xstatic void
  888. Xzprinto(z, width)
  889. X    ZVALUE z;
  890. X    long width;
  891. X{
  892. X    register HALF *hp;    /* current word to print */
  893. X    int len;        /* number of halfwords to type */
  894. X    int num1, num2;        /* numbers to type */
  895. X    int rem;        /* remainder number of halfwords */
  896. X
  897. X    if (isneg(z))
  898. X        PUTCHAR('-');
  899. X    len = z.len;
  900. X    if ((len == 1) && (*z.v <= (FULL) 7)) {
  901. X        num1 = '0' + *z.v;
  902. X        PUTCHAR(num1);
  903. X        return;
  904. X    }
  905. X    hp = z.v + len - 1;
  906. X    rem = len % 3;
  907. X    switch (rem) {    /* handle odd amounts first */
  908. X        case 0:
  909. X            num1 = (((FULL) hp[0]) << 8) + (((FULL) hp[-1]) >> 8);
  910. X            num2 = (((FULL) (hp[-1] & 0xff)) << 16) + ((FULL) hp[-2]);
  911. X            rem = 3;
  912. X            break;
  913. X        case 1:
  914. X            num1 = 0;
  915. X            num2 = (FULL) hp[0];
  916. X            break;
  917. X        case 2:
  918. X            num1 = (((FULL) hp[0]) >> 8);
  919. X            num2 = (((FULL) (hp[0] & 0xff)) << 16) + ((FULL) hp[-1]);
  920. X            break;
  921. X    }
  922. X    if (num1)
  923. X        PRINTF2("0%o%08o", num1, num2);
  924. X    else
  925. X        PRINTF1("0%o", num2);
  926. X    len -= rem;
  927. X    hp -= rem;
  928. X    while (len > 0) {    /* finish in groups of 3 halfwords */
  929. X        num1 = (((FULL) hp[0]) << 8) + (((FULL) hp[-1]) >> 8);
  930. X        num2 = (((FULL) (hp[-1] & 0xff)) << 16) + ((FULL) hp[-2]);
  931. X        PRINTF2("%08o%08o", num1, num2);
  932. X        hp -= 3;
  933. X        len -= 3;
  934. X    }
  935. X}
  936. X
  937. X
  938. X/*
  939. X * Print a decimal integer to the terminal.
  940. X * This works by dividing the number by 10^2^N for some N, and
  941. X * then doing this recursively on the quotient and remainder.
  942. X * Decimals supplies number of decimal places to print, with a decimal
  943. X * point at the right location, with zero meaning no decimal point.
  944. X * Width is the number of columns to print the number in, including the
  945. X * decimal point and sign if required.  If zero, no extra output is done.
  946. X * If positive, leading spaces are typed if necessary. If negative, trailing
  947. X * spaces are typed if necessary.  As examples of the effects of these values,
  948. X * (345,0,0) = "345", (345,2,0) = "3.45", (345,5,8) = "  .00345".
  949. X */
  950. Xstatic void
  951. Xzprintval(z, decimals, width)
  952. X    ZVALUE z;        /* number to be printed */
  953. X    long decimals;        /* number of decimal places */
  954. X    long width;        /* number of columns to print in */
  955. X{
  956. X    int depth;        /* maximum depth */
  957. X    int n;            /* current index into array */
  958. X    int i;            /* number to print */
  959. X    long leadspaces;    /* number of leading spaces to print */
  960. X    long putpoint;        /* digits until print decimal point */
  961. X    long digits;        /* number of digits of raw number */
  962. X    BOOL output;        /* TRUE if have output something */
  963. X    BOOL neg;        /* TRUE if negative */
  964. X    ZVALUE quo, rem;    /* quotient and remainder */
  965. X    ZVALUE leftnums[32];    /* left parts of the number */
  966. X    ZVALUE rightnums[32];    /* right parts of the number */
  967. X
  968. X    if (decimals < 0)
  969. X        decimals = 0;
  970. X    if (width < 0)
  971. X        width = 0;
  972. X    neg = (z.sign != 0);
  973. X
  974. X    leadspaces = width - neg - (decimals > 0);
  975. X    z.sign = 0;
  976. X    /*
  977. X     * Find the 2^N power of ten which is greater than or equal
  978. X     * to the number, calculating it the first time if necessary.
  979. X     */
  980. X    _tenpowers_[0] = _ten_;
  981. X    depth = 0;
  982. X    while ((_tenpowers_[depth].len < z.len) || (zrel(_tenpowers_[depth], z) <= 0)) {
  983. X        depth++;
  984. X        if (_tenpowers_[depth].len == 0)
  985. X            zsquare(_tenpowers_[depth-1], &_tenpowers_[depth]);
  986. X    }
  987. X    /*
  988. X     * Divide by smaller 2^N powers of ten until the parts are small
  989. X     * enough to output.  This algorithm walks through a binary tree
  990. X     * where each node is a piece of the number to print, and such that
  991. X     * we visit left nodes first.  We do the needed recursion in line.
  992. X     */
  993. X    digits = 1;
  994. X    output = FALSE;
  995. X    n = 0;
  996. X    putpoint = 0;
  997. X    rightnums[0].len = 0;
  998. X    leftnums[0] = z;
  999. X    for (;;) {
  1000. X        while (n < depth) {
  1001. X            i = depth - n - 1;
  1002. X            zdiv(leftnums[n], _tenpowers_[i], &quo, &rem);
  1003. X            if (!iszero(quo))
  1004. X                digits += (1L << i);
  1005. X            n++;
  1006. X            leftnums[n] = quo;
  1007. X            rightnums[n] = rem;
  1008. X        }
  1009. X        i = leftnums[n].v[0];
  1010. X        if (output || i || (n == 0)) {
  1011. X            if (!output) {
  1012. X                output = TRUE;
  1013. X                if (decimals > digits)
  1014. X                    leadspaces -= decimals;
  1015. X                else
  1016. X                    leadspaces -= digits;
  1017. X                while (--leadspaces >= 0)
  1018. X                    PUTCHAR(' ');
  1019. X                if (neg)
  1020. X                    PUTCHAR('-');
  1021. X                if (decimals) {
  1022. X                    putpoint = (digits - decimals);
  1023. X                    if (putpoint <= 0) {
  1024. X                        PUTCHAR('.');
  1025. X                        while (++putpoint <= 0)
  1026. X                            PUTCHAR('0');
  1027. X                        putpoint = 0;
  1028. X                    }
  1029. X                }
  1030. X            }
  1031. X            i += '0';
  1032. X            PUTCHAR(i);
  1033. X            if (--putpoint == 0)
  1034. X                PUTCHAR('.');
  1035. X        }
  1036. X        while (rightnums[n].len == 0) {
  1037. X            if (n <= 0)
  1038. X                return;
  1039. X            if (leftnums[n].len)
  1040. X                freeh(leftnums[n].v);
  1041. X            n--;
  1042. X        }
  1043. X        freeh(leftnums[n].v);
  1044. X        leftnums[n] = rightnums[n];
  1045. X        rightnums[n].len = 0;
  1046. X    }
  1047. X}
  1048. X
  1049. X
  1050. X/*
  1051. X * Convert a string to a number in rational, floating point,
  1052. X * exponential notation, hex, or octal.
  1053. X *    q = atoq(string);
  1054. X */
  1055. XNUMBER *
  1056. Xatoq(s)
  1057. X    register char *s;
  1058. X{
  1059. X    register NUMBER *q;
  1060. X    register char *t;
  1061. X    ZVALUE div, newnum, newden, tmp;
  1062. X    long decimals, exp;
  1063. X    BOOL hex, negexp;
  1064. X
  1065. X    q = qalloc();
  1066. X    decimals = 0;
  1067. X    exp = 0;
  1068. X    negexp = FALSE;
  1069. X    hex = FALSE;
  1070. X    t = s;
  1071. X    if ((*t == '+') || (*t == '-'))
  1072. X        t++;
  1073. X    if ((*t == '0') && ((t[1] == 'x') || (t[1] == 'X'))) {
  1074. X        hex = TRUE;
  1075. X        t += 2;
  1076. X    }
  1077. X    while (((*t >= '0') && (*t <= '9')) || (hex &&
  1078. X        (((*t >= 'a') && (*t <= 'f')) || ((*t >= 'A') && (*t <= 'F')))))
  1079. X            t++;
  1080. X    if (*t == '/') {
  1081. X        t++;
  1082. X        atoz(t, &q->den);
  1083. X    } else if ((*t == '.') || (*t == 'e') || (*t == 'E')) {
  1084. X        if (*t == '.') {
  1085. X            t++;
  1086. X            while ((*t >= '0') && (*t <= '9')) {
  1087. X                t++;
  1088. X                decimals++;
  1089. X            }
  1090. X        }
  1091. X        /*
  1092. X         * Parse exponent if any
  1093. X         */
  1094. X        if ((*t == 'e') || (*t == 'E')) {
  1095. X            t++;
  1096. X            if (*t == '+')
  1097. X                t++;
  1098. X            else if (*t == '-') {
  1099. X                negexp = TRUE;
  1100. X                t++;
  1101. X            }
  1102. X            while ((*t >= '0') && (*t <= '9')) {
  1103. X                exp = (exp * 10) + *t++ - '0';
  1104. X                if (exp > 1000000)
  1105. X                    error("Exponent too large");
  1106. X            }
  1107. X        }
  1108. X        ztenpow(decimals, &q->den);
  1109. X    }
  1110. X    atoz(s, &q->num);
  1111. X    if (qiszero(q)) {
  1112. X        qfree(q);
  1113. X        return qlink(&_qzero_);
  1114. X    }
  1115. X    /*
  1116. X     * Apply the exponential if any
  1117. X     */
  1118. X    if (exp) {
  1119. X        ztenpow(exp, &tmp);
  1120. X        if (negexp) {
  1121. X            zmul(q->den, tmp, &newden);
  1122. X            freeh(q->den.v);
  1123. X            q->den = newden;
  1124. X        } else {
  1125. X            zmul(q->num, tmp, &newnum);
  1126. X            freeh(q->num.v);
  1127. X            q->num = newnum;
  1128. X        }
  1129. X        freeh(tmp.v);
  1130. X    }
  1131. X    /*
  1132. X     * Reduce the fraction to lowest terms
  1133. X     */
  1134. X    if (isunit(q->num) || isunit(q->den))
  1135. X        return q;
  1136. X    zgcd(q->num, q->den, &div);
  1137. X    if (isunit(div))
  1138. X        return q;
  1139. X    zquo(q->num, div, &newnum);
  1140. X    freeh(q->num.v);
  1141. X    zquo(q->den, div, &newden);
  1142. X    freeh(q->den.v);
  1143. X    q->num = newnum;
  1144. X    q->den = newden;
  1145. X    return q;
  1146. X}
  1147. X
  1148. X
  1149. X/*
  1150. X * Read an integer value in decimal, hex, octal, or binary.
  1151. X * Hex numbers are indicated by a leading "0x", binary with a leading "0b",
  1152. X * and octal by a leading "0".  Periods are skipped over, but any other
  1153. X * extraneous character stops the scan.
  1154. X */
  1155. Xstatic void
  1156. Xatoz(s, res)
  1157. X    register char *s;
  1158. X    ZVALUE *res;
  1159. X{
  1160. X    ZVALUE z, ztmp, digit;
  1161. X    HALF digval;
  1162. X    BOOL minus;
  1163. X    long shift;
  1164. X
  1165. X    minus = FALSE;
  1166. X    shift = 0;
  1167. X    if (*s == '+')
  1168. X        s++;
  1169. X    else if (*s == '-') {
  1170. X        minus = TRUE;
  1171. X        s++;
  1172. X    }
  1173. X    if (*s == '0') {        /* possibly hex, octal, or binary */
  1174. X        s++;
  1175. X        if ((*s >= '0') && (*s <= '7')) {
  1176. X            shift = 3;
  1177. X        } else if ((*s == 'x') || (*s == 'X')) {
  1178. X            shift = 4;
  1179. X            s++;
  1180. X        } else if ((*s == 'b') || (*s == 'B')) {
  1181. X            shift = 1;
  1182. X            s++;
  1183. X        }
  1184. X    }
  1185. X    digit.v = &digval;
  1186. X    digit.len = 1;
  1187. X    digit.sign = 0;
  1188. X    z = _zero_;
  1189. X    while (*s) {
  1190. X        digval = *s++;
  1191. X        if ((digval >= '0') && (digval <= '9'))
  1192. X            digval -= '0';
  1193. X        else if ((digval >= 'a') && (digval <= 'f') && shift)
  1194. X            digval -= ('a' - 10);
  1195. X        else if ((digval >= 'A') && (digval <= 'F') && shift)
  1196. X            digval -= ('A' - 10);
  1197. X        else if (digval == '.')
  1198. X            continue;
  1199. X        else
  1200. X            break;
  1201. X        if (shift)
  1202. X            zshift(z, shift, &ztmp);
  1203. X        else
  1204. X            zmuli(z, 10L, &ztmp);
  1205. X        freeh(z.v);
  1206. X        zadd(ztmp, digit, &z);
  1207. X        freeh(ztmp.v);
  1208. X    }
  1209. X    trim(&z);
  1210. X    if (minus && !iszero(z))
  1211. X        z.sign = 1;
  1212. X    *res = z;
  1213. X}
  1214. X
  1215. X
  1216. X/*
  1217. X * Parse a number in any of the various legal forms, and return the count
  1218. X * of characters that are part of a legal number.  Numbers can be either a
  1219. X * decimal integer, possibly two decimal integers separated with a slash, a
  1220. X * floating point or exponential number, a hex number beginning with "0x",
  1221. X * a binary number beginning with "0b", or an octal number beginning with "0".
  1222. X * The flags argument modifies the end of number testing for ease in handling
  1223. X * fractions or complex numbers.  Minus one is returned if the number format
  1224. X * is definitely illegal.
  1225. X */
  1226. Xlong
  1227. Xqparse(cp, flags)
  1228. X    register char *cp;
  1229. X{
  1230. X    char *oldcp;
  1231. X
  1232. X    oldcp = cp;
  1233. X    if ((*cp == '+') || (*cp == '-'))
  1234. X        cp++;
  1235. X    if ((*cp == '+') || (*cp == '-'))
  1236. X        return -1;
  1237. X    if ((*cp == '0') && ((cp[1] == 'x') || (cp[1] == 'X'))) {    /* hex */
  1238. X        cp += 2;
  1239. X        while (((*cp >= '0') && (*cp <= '9')) ||
  1240. X            ((*cp >= 'a') && (*cp <= 'f')) ||
  1241. X            ((*cp >= 'A') && (*cp <= 'F')))
  1242. X                cp++;
  1243. X        goto done;
  1244. X    }
  1245. X    if ((*cp == '0') && ((cp[1] == 'b') || (cp[1] == 'B'))) {    /* binary */
  1246. X        cp += 2;
  1247. X        while ((*cp == '0') || (*cp == '1'))
  1248. X            cp++;
  1249. X        goto done;
  1250. X    }
  1251. X    if ((*cp == '0') && (cp[1] >= '0') && (cp[1] <= '9')) { /* octal */
  1252. X        while ((*cp >= '0') && (*cp <= '7'))
  1253. X            cp++;
  1254. X        goto done;
  1255. X    }
  1256. X    /*
  1257. X     * Number is decimal, but can still be a fraction or real or exponential.
  1258. X     */
  1259. X    while ((*cp >= '0') && (*cp <= '9'))
  1260. X        cp++;
  1261. X    if (*cp == '/' && flags & QPF_SLASH) {    /* fraction */
  1262. X        cp++;
  1263. X        while ((*cp >= '0') && (*cp <= '9'))
  1264. X            cp++;
  1265. X        goto done;
  1266. X    }
  1267. X    if (*cp == '.') {    /* floating point */
  1268. X        cp++;
  1269. X        while ((*cp >= '0') && (*cp <= '9'))
  1270. X            cp++;
  1271. X    }
  1272. X    if ((*cp == 'e') || (*cp == 'E')) {    /* exponential */
  1273. X        cp++;
  1274. X        if ((*cp == '+') || (*cp == '-'))
  1275. X            cp++;
  1276. X        if ((*cp == '+') || (*cp == '-'))
  1277. X            return -1;
  1278. X        while ((*cp >= '0') && (*cp <= '9'))
  1279. X            cp++;
  1280. X    }
  1281. X
  1282. Xdone:
  1283. X    if (((*cp == 'i') || (*cp == 'I')) && (flags & QPF_IMAG))
  1284. X        cp++;
  1285. X    if ((*cp == '.') || ((*cp == '/') && (flags & QPF_SLASH)) ||
  1286. X        ((*cp >= '0') && (*cp <= '9')) ||
  1287. X        ((*cp >= 'a') && (*cp <= 'z')) ||
  1288. X        ((*cp >= 'A') && (*cp <= 'Z')))
  1289. X            return -1;
  1290. X    return (cp - oldcp);
  1291. X}
  1292. X
  1293. X/* END CODE */
  1294. END_OF_FILE
  1295. if test 26180 -ne `wc -c <'io.c'`; then
  1296.     echo shar: \"'io.c'\" unpacked with wrong size!
  1297. fi
  1298. # end of 'io.c'
  1299. fi
  1300. if test -f 'qfunc.c' -a "${1}" != "-c" ; then 
  1301.   echo shar: Will not clobber existing file \"'qfunc.c'\"
  1302. else
  1303. echo shar: Extracting \"'qfunc.c'\" \(24256 characters\)
  1304. sed "s/^X//" >'qfunc.c' <<'END_OF_FILE'
  1305. X/*
  1306. X * Copyright (c) 1992 David I. Bell
  1307. X * Permission is granted to use, distribute, or modify this source,
  1308. X * provided that this copyright notice remains intact.
  1309. X *
  1310. X * Extended precision rational arithmetic non-primitive functions
  1311. X */
  1312. X
  1313. X#include "math.h"
  1314. X
  1315. X
  1316. XNUMBER *_epsilon_;    /* default precision for real functions */
  1317. Xlong _epsilonprec_;    /* bits of precision for epsilon */
  1318. X
  1319. X#if 0
  1320. Xstatic char *abortmsg = "Calculation aborted";
  1321. Xstatic char *memmsg = "Not enough memory";
  1322. X#endif
  1323. X
  1324. X
  1325. X/*
  1326. X * Set the default precision for real calculations.
  1327. X * The precision must be between zero and one.
  1328. X */
  1329. Xvoid
  1330. Xsetepsilon(q)
  1331. X    NUMBER *q;        /* number to be set as the new epsilon */
  1332. X{
  1333. X    NUMBER *old;
  1334. X
  1335. X    if (qisneg(q) || qiszero(q) || (qreli(q, 1L) >= 0))
  1336. X        error("Epsilon value must be between zero and one");
  1337. X    old = _epsilon_;
  1338. X    _epsilonprec_ = qprecision(q);
  1339. X    _epsilon_ = qlink(q);
  1340. X    if (old)
  1341. X        qfree(old);
  1342. X}
  1343. X
  1344. X
  1345. X/*
  1346. X * Return the inverse of one number modulo another.
  1347. X * That is, find x such that:
  1348. X *    Ax = 1 (mod B)
  1349. X * Returns zero if the numbers are not relatively prime (temporary hack).
  1350. X */
  1351. XNUMBER *
  1352. Xqminv(q1, q2)
  1353. X    NUMBER *q1, *q2;
  1354. X{
  1355. X    NUMBER *r;
  1356. X
  1357. X    if (qisfrac(q1) || qisfrac(q2))
  1358. X        error("Non-integers for minv");
  1359. X    r = qalloc();
  1360. X    if (zmodinv(q1->num, q2->num, &r->num)) {
  1361. X        qfree(r);
  1362. X        return qlink(&_qzero_);
  1363. X    }
  1364. X    return r;
  1365. X}
  1366. X
  1367. X
  1368. X/*
  1369. X * Return the modulo of one number raised to another.
  1370. X * Here q1 is the number to be raised, q2 is the power to raise it to,
  1371. X * and q3 is the number to take the modulo with the result.
  1372. X * The second and third numbers are assumed nonnegative.
  1373. X * Returned answer is non-negative.
  1374. X *    q4 = qpowermod(q1, q2, q3);
  1375. X */
  1376. XNUMBER *
  1377. Xqpowermod(q1, q2, q3)
  1378. X    NUMBER *q1, *q2, *q3;
  1379. X{
  1380. X    NUMBER *r;
  1381. X
  1382. X    if (qisfrac(q1) || qisfrac(q2) || qisfrac(q3))
  1383. X        error("Non-integers for powermod");
  1384. X    r = qalloc();
  1385. X    zpowermod(q1->num, q2->num, q3->num, &r->num);
  1386. X    return r;
  1387. X}
  1388. X
  1389. X
  1390. X/*
  1391. X * Return the power function of one number with another.
  1392. X * The power must be integral.
  1393. X *    q3 = qpowi(q1, q2);
  1394. X */
  1395. XNUMBER *
  1396. Xqpowi(q1, q2)
  1397. X    NUMBER *q1, *q2;
  1398. X{
  1399. X    register NUMBER *r;
  1400. X    BOOL invert, sign;
  1401. X    ZVALUE num, den, z2;
  1402. X
  1403. X    if (qisfrac(q2))
  1404. X        error("Raising number to fractional power");
  1405. X    num = q1->num;
  1406. X    den = q1->den;
  1407. X    z2 = q2->num;
  1408. X    sign = (num.sign && isodd(z2));
  1409. X    invert = z2.sign;
  1410. X    num.sign = 0;
  1411. X    z2.sign = 0;
  1412. X    /*
  1413. X    * Check for trivial cases first.
  1414. X    */
  1415. X    if (iszero(num)) {    /* zero raised to a power */
  1416. X        if (invert || iszero(z2))
  1417. X            error("Zero raised to non-positive power");
  1418. X        return qlink(&_qzero_);
  1419. X    }
  1420. X    if (isunit(num) && isunit(den)) {    /* 1 or -1 raised to a power */
  1421. X        r = (sign ? q1 : &_qone_);
  1422. X        r->links++;
  1423. X        return r;
  1424. X    }
  1425. X    if (iszero(z2))    /* raising to zeroth power */
  1426. X        return qlink(&_qone_);
  1427. X    if (isunit(z2)) {    /* raising to power 1 or -1 */
  1428. X        if (invert)
  1429. X            return qinv(q1);
  1430. X        return qlink(q1);
  1431. X    }
  1432. X    /*
  1433. X     * Not a trivial case.  Do the real work.
  1434. X     */
  1435. X    r = qalloc();
  1436. X    if (!isunit(num))
  1437. X        zpowi(num, z2, &r->num);
  1438. X    if (!isunit(den))
  1439. X        zpowi(den, z2, &r->den);
  1440. X    if (invert) {
  1441. X        z2 = r->num;
  1442. X        r->num = r->den;
  1443. X        r->den = z2;
  1444. X    }
  1445. X    r->num.sign = sign;
  1446. X    return r;
  1447. X}
  1448. X
  1449. X
  1450. X/*
  1451. X * Given the legs of a right triangle, compute its hypothenuse within
  1452. X * the specified error.  This is sqrt(a^2 + b^2).
  1453. X */
  1454. XNUMBER *
  1455. Xqhypot(q1, q2, epsilon)
  1456. X    NUMBER *q1, *q2, *epsilon;
  1457. X{
  1458. X    NUMBER *tmp1, *tmp2, *tmp3;
  1459. X
  1460. X    if (qisneg(epsilon) || qiszero(epsilon))
  1461. X        error("Bad epsilon value for hypot");
  1462. X    if (qiszero(q1))
  1463. X        return qabs(q2);
  1464. X    if (qiszero(q2))
  1465. X        return qabs(q1);
  1466. X    tmp1 = qsquare(q1);
  1467. X    tmp2 = qsquare(q2);
  1468. X    tmp3 = qadd(tmp1, tmp2);
  1469. X    qfree(tmp1);
  1470. X    qfree(tmp2);
  1471. X    tmp1 = qsqrt(tmp3, epsilon);
  1472. X    qfree(tmp3);
  1473. X    return tmp1;
  1474. X}
  1475. X
  1476. X
  1477. X/*
  1478. X * Given one leg of a right triangle with unit hypothenuse, calculate
  1479. X * the other leg within the specified error.  This is sqrt(1 - a^2).
  1480. X * If the wantneg flag is nonzero, then negative square root is returned.
  1481. X */
  1482. XNUMBER *
  1483. Xqlegtoleg(q, epsilon, wantneg)
  1484. X    NUMBER *q, *epsilon;
  1485. X    BOOL wantneg;
  1486. X{
  1487. X    NUMBER *qt, *res, qtmp;
  1488. X    ZVALUE num, ztmp1, ztmp2;
  1489. X
  1490. X    if (qisneg(epsilon) || qiszero(epsilon))
  1491. X        error("Bad epsilon value for legtoleg");
  1492. X    if (qisunit(q))
  1493. X        return qlink(&_qzero_);
  1494. X    if (qiszero(q)) {
  1495. X        if (wantneg)
  1496. X            return qlink(&_qnegone_);
  1497. X        return qlink(&_qone_);
  1498. X    }
  1499. X    num = q->num;
  1500. X    num.sign = 0;
  1501. X    if (zrel(num, q->den) >= 0)
  1502. X        error("Leg too large in legtoleg");
  1503. X    zsquare(q->den, &ztmp1);
  1504. X    zsquare(num, &ztmp2);
  1505. X    zsub(ztmp1, ztmp2, &qtmp.num);
  1506. X    freeh(ztmp1.v);
  1507. X    freeh(ztmp2.v);
  1508. X    qtmp.den = _one_;
  1509. X    qt = qsqrt(&qtmp, epsilon);
  1510. X    freeh(qtmp.num.v);
  1511. X    qtmp.num = q->den;
  1512. X    res = qdiv(qt, &qtmp);
  1513. X    qfree(qt);
  1514. X    qt = qbappr(res, epsilon);
  1515. X    qfree(res);
  1516. X    if (wantneg) {
  1517. X        res = qneg(qt);
  1518. X        qfree(qt);
  1519. X        qt = res;
  1520. X    }
  1521. X    return qt;
  1522. X}
  1523. X
  1524. X
  1525. X/*
  1526. X * Compute the square root of a number to within the specified error.
  1527. X * If the number is an exact square, the exact result is returned.
  1528. X *    q3 = qsqrt(q1, q2);
  1529. X */
  1530. XNUMBER *
  1531. Xqsqrt(q1, epsilon)
  1532. X    register NUMBER *q1, *epsilon;
  1533. X{
  1534. X    long bits, bits2;    /* number of bits of precision */
  1535. X    int exact;
  1536. X    NUMBER *r;
  1537. X    ZVALUE t1, t2;
  1538. X
  1539. X    if (qisneg(q1))
  1540. X        error("Square root of negative number");
  1541. X    if (qisneg(epsilon) || qiszero(epsilon))
  1542. X        error("Bad epsilon value for sqrt");
  1543. X    if (qiszero(q1))
  1544. X        return qlink(&_qzero_);
  1545. X    if (qisunit(q1))
  1546. X        return qlink(&_qone_);
  1547. X    if (qiszero(epsilon) && qisint(q1) && istiny(q1->num) && (*q1->num.v <= 3))
  1548. X        return qlink(&_qone_);
  1549. X    bits = zhighbit(epsilon->den) - zhighbit(epsilon->num) + 1;
  1550. X    if (bits < 0)
  1551. X        bits = 0;
  1552. X    bits2 = zhighbit(q1->num) - zhighbit(q1->den) + 1;
  1553. X    if (bits2 > 0)
  1554. X        bits += bits2;
  1555. X    r = qalloc();
  1556. X    zshift(q1->num, bits * 2, &t2);
  1557. X    zmul(q1->den, t2, &t1);
  1558. X    freeh(t2.v);
  1559. X    exact = zsqrt(t1, &t2);
  1560. X    freeh(t1.v);
  1561. X    if (exact) {
  1562. X        zshift(q1->den, bits, &t1);
  1563. X        zreduce(t2, t1, &r->num, &r->den);
  1564. X    } else {
  1565. X        zquo(t2, q1->den, &t1);
  1566. X        freeh(t2.v);
  1567. X        zbitvalue(bits, &t2);
  1568. X        zreduce(t1, t2, &r->num, &r->den);
  1569. X    }
  1570. X    freeh(t1.v);
  1571. X    freeh(t2.v);
  1572. X    if (qiszero(r)) {
  1573. X        qfree(r);
  1574. X        r = qlink(&_qzero_);
  1575. X    }
  1576. X    return r;
  1577. X}
  1578. X
  1579. X
  1580. X/*
  1581. X * Calculate the integral part of the square root of a number.
  1582. X * Example:  qisqrt(13) = 3.
  1583. X */
  1584. XNUMBER *
  1585. Xqisqrt(q)
  1586. X    NUMBER *q;
  1587. X{
  1588. X    NUMBER *r;
  1589. X    ZVALUE tmp;
  1590. X
  1591. X    if (qisneg(q))
  1592. X        error("Square root of negative number");
  1593. X    if (qiszero(q))
  1594. X        return qlink(&_qzero_);
  1595. X    if (qisint(q) && istiny(q->num) && (z1tol(q->num) < 4))
  1596. X        return qlink(&_qone_);
  1597. X    r = qalloc();
  1598. X    if (qisint(q)) {
  1599. X        (void) zsqrt(q->num, &r->num);
  1600. X        return r;
  1601. X    }
  1602. X    zquo(q->num, q->den, &tmp);
  1603. X    (void) zsqrt(tmp, &r->num);
  1604. X    freeh(tmp.v);
  1605. X    return r;
  1606. X}
  1607. X
  1608. X
  1609. X/*
  1610. X * Return whether or not a number is an exact square.
  1611. X */
  1612. XBOOL
  1613. Xqissquare(q)
  1614. X    NUMBER *q;
  1615. X{
  1616. X    BOOL flag;
  1617. X
  1618. X    flag = zissquare(q->num);
  1619. X    if (qisint(q) || !flag)
  1620. X        return flag;
  1621. X    return zissquare(q->den);
  1622. X}
  1623. X
  1624. X
  1625. X/*
  1626. X * Compute the greatest integer of the Kth root of a number.
  1627. X * Example:  qiroot(85, 3) = 4.
  1628. X */
  1629. XNUMBER *
  1630. Xqiroot(q1, q2)
  1631. X    register NUMBER *q1, *q2;
  1632. X{
  1633. X    NUMBER *r;
  1634. X    ZVALUE tmp;
  1635. X
  1636. X    if (qisneg(q2) || qiszero(q2) || qisfrac(q2))
  1637. X        error("Taking number to bad root value");
  1638. X    if (qiszero(q1))
  1639. X        return qlink(&_qzero_);
  1640. X    if (qisone(q1) || qisone(q2))
  1641. X        return qlink(q1);
  1642. X    if (qistwo(q2))
  1643. X        return qisqrt(q1);
  1644. X    r = qalloc();
  1645. X    if (qisint(q1)) {
  1646. X        zroot(q1->num, q2->num, &r->num);
  1647. X        return r;
  1648. X    }
  1649. X    zquo(q1->num, q1->den, &tmp);
  1650. X    zroot(tmp, q2->num, &r->num);
  1651. X    freeh(tmp.v);
  1652. X    return r;
  1653. X}
  1654. X
  1655. X
  1656. X/*
  1657. X * Return the greatest integer of the base 2 log of a number.
  1658. X * This is the number such that  1 <= x / log2(x) < 2.
  1659. X * Examples:  qilog2(8) = 3, qilog2(1.3) = 1, qilog2(1/7) = -3.
  1660. X */
  1661. Xlong
  1662. Xqilog2(q)
  1663. X    NUMBER *q;        /* number to take log of */
  1664. X{
  1665. X    long n;            /* power of two */
  1666. X    int c;            /* result of comparison */
  1667. X    ZVALUE tmp;        /* temporary value */
  1668. X
  1669. X    if (qisneg(q) || qiszero(q))
  1670. X        error("Non-positive number for log2");
  1671. X    if (qisint(q))
  1672. X        return zhighbit(q->num);
  1673. X    n = zhighbit(q->num) - zhighbit(q->den);
  1674. X    if (n == 0)
  1675. X        c = zrel(q->num, q->den);
  1676. X    else if (n > 0) {
  1677. X        zshift(q->den, n, &tmp);
  1678. X        c = zrel(q->num, tmp);
  1679. X    } else {
  1680. X        zshift(q->num, n, &tmp);
  1681. X        c = zrel(tmp, q->den);
  1682. X    }
  1683. X    if (n)
  1684. X        freeh(tmp.v);
  1685. X    if (c < 0)
  1686. X        n--;
  1687. X    return n;
  1688. X}
  1689. X
  1690. X
  1691. X/*
  1692. X * Return the greatest integer of the base 10 log of a number.
  1693. X * This is the number such that  1 <= x / log10(x) < 10.
  1694. X * Examples:  qilog10(100) = 2, qilog10(12.3) = 1, qilog10(.023) = -2.
  1695. X */
  1696. Xlong
  1697. Xqilog10(q)
  1698. X    NUMBER *q;        /* number to take log of */
  1699. X{
  1700. X    long n;            /* log value */
  1701. X    ZVALUE temp;        /* temporary value */
  1702. X
  1703. X    if (qisneg(q) || qiszero(q))
  1704. X        error("Non-positive number for log10");
  1705. X    if (qisint(q))
  1706. X        return zlog10(q->num);
  1707. X    /*
  1708. X     * The number is not an integer.
  1709. X     * Compute the result if the number is greater than one.
  1710. X     */
  1711. X    if ((q->num.len > q->den.len) ||
  1712. X        ((q->num.len == q->den.len) && (zrel(q->num, q->den) > 0))) {
  1713. X            zquo(q->num, q->den, &temp);
  1714. X            n = zlog10(temp);
  1715. X            freeh(temp.v);
  1716. X            return n;
  1717. X    }
  1718. X    /*
  1719. X     * Here if the number is less than one.
  1720. X     * If the number is the inverse of a power of ten, then the obvious answer
  1721. X     * will be off by one.  Subtracting one if the number is the inverse of an
  1722. X     * integer will fix it.
  1723. X     */
  1724. X    if (isunit(q->num))
  1725. X        zsub(q->den, _one_, &temp);
  1726. X    else
  1727. X        zquo(q->den, q->num, &temp);
  1728. X    n = -zlog10(temp) - 1;
  1729. X    freeh(temp.v);
  1730. X    return n;
  1731. X}
  1732. X
  1733. X
  1734. X/*
  1735. X * Return the number of digits in a number, ignoring the sign.
  1736. X * For fractions, this is the number of digits of its greatest integer.
  1737. X * Examples: qdigits(3456) = 4, qdigits(-23.45) = 2, qdigits(.0120) = 1.
  1738. X */
  1739. Xlong
  1740. Xqdigits(q)
  1741. X    NUMBER *q;        /* number to count digits of */
  1742. X{
  1743. X    long n;            /* number of digits */
  1744. X    ZVALUE temp;        /* temporary value */
  1745. X
  1746. X    if (qisint(q))
  1747. X        return zdigits(q->num);
  1748. X    zquo(q->num, q->den, &temp);
  1749. X    n = zdigits(temp);
  1750. X    freeh(temp.v);
  1751. X    return n;
  1752. X}
  1753. X
  1754. X
  1755. X/*
  1756. X * Return the digit at the specified decimal place of a number represented
  1757. X * in floating point.  The lowest digit of the integral part of a number
  1758. X * is the zeroth decimal place.  Negative decimal places indicate digits
  1759. X * to the right of the decimal point.  Examples: qdigit(1234.5678, 1) = 3,
  1760. X * qdigit(1234.5678, -3) = 7.
  1761. X */
  1762. XFLAG
  1763. Xqdigit(q, n)
  1764. X    NUMBER *q;
  1765. X    long n;
  1766. X{
  1767. X    ZVALUE tenpow, tmp1, tmp2;
  1768. X    FLAG res;
  1769. X
  1770. X    /*
  1771. X     * Zero number or negative decimal place of integer is trivial.
  1772. X     */
  1773. X    if (qiszero(q) || (qisint(q) && (n < 0)))
  1774. X        return 0;
  1775. X    /*
  1776. X     * For non-negative decimal places, answer is easy.
  1777. X     */
  1778. X    if (n >= 0) {
  1779. X        if (qisint(q))
  1780. X            return zdigit(q->num, n);
  1781. X        zquo(q->num, q->den, &tmp1);
  1782. X        res = zdigit(tmp1, n);
  1783. X        freeh(tmp1.v);
  1784. X        return res;
  1785. X    }
  1786. X    /*
  1787. X     * Fractional value and want negative digit, must work harder.
  1788. X     */
  1789. X    ztenpow(-n, &tenpow);
  1790. X    zmul(q->num, tenpow, &tmp1);
  1791. X    freeh(tenpow.v);
  1792. X    zquo(tmp1, q->den, &tmp2);
  1793. X    res = zmodi(tmp2, 10L);
  1794. X    freeh(tmp1.v);
  1795. X    freeh(tmp2.v);
  1796. X    return res;
  1797. X}
  1798. X
  1799. X
  1800. X/*
  1801. X * Return whether or not a bit is set at the specified bit position in a
  1802. X * number.  The lowest bit of the integral part of a number is the zeroth
  1803. X * bit position.  Negative bit positions indicate bits to the right of the
  1804. X * binary decimal point.  Examples: qdigit(17.1, 0) = 1, qdigit(17.1, -1) = 0.
  1805. X */
  1806. XBOOL
  1807. Xqisset(q, n)
  1808. X    NUMBER *q;
  1809. X    long n;
  1810. X{
  1811. X    NUMBER *qtmp1, *qtmp2;
  1812. X    ZVALUE ztmp;
  1813. X    BOOL res;
  1814. X
  1815. X    /*
  1816. X     * Zero number or negative bit position place of integer is trivial.
  1817. X     */
  1818. X    if (qiszero(q) || (qisint(q) && (n < 0)))
  1819. X        return FALSE;
  1820. X    /*
  1821. X     * For non-negative bit positions, answer is easy.
  1822. X     */
  1823. X    if (n >= 0) {
  1824. X        if (qisint(q))
  1825. X            return zisset(q->num, n);
  1826. X        zquo(q->num, q->den, &ztmp);
  1827. X        res = zisset(ztmp, n);
  1828. X        freeh(ztmp.v);
  1829. X        return res;
  1830. X    }
  1831. X    /*
  1832. X     * Fractional value and want negative bit position, must work harder.
  1833. X     */
  1834. X    qtmp1 = qscale(q, -n);
  1835. X    qtmp2 = qint(qtmp1);
  1836. X    qfree(qtmp1);
  1837. X    res = ((qtmp2->num.v[0] & 0x01) != 0);
  1838. X    qfree(qtmp2);
  1839. X    return res;
  1840. X}
  1841. X
  1842. X
  1843. X/*
  1844. X * Compute the factorial of an integer.
  1845. X *    q2 = qfact(q1);
  1846. X */
  1847. XNUMBER *
  1848. Xqfact(q)
  1849. X    register NUMBER *q;
  1850. X{
  1851. X    register NUMBER *r;
  1852. X
  1853. X    if (qisfrac(q))
  1854. X        error("Non-integral factorial");
  1855. X    if (qiszero(q) || isone(q->num))
  1856. X        return qlink(&_qone_);
  1857. X    r = qalloc();
  1858. X    zfact(q->num, &r->num);
  1859. X    return r;
  1860. X}
  1861. X
  1862. X
  1863. X/*
  1864. X * Compute the product of the primes less than or equal to a number.
  1865. X *    q2 = qpfact(q1);
  1866. X */
  1867. XNUMBER *
  1868. Xqpfact(q)
  1869. X    register NUMBER *q;
  1870. X{
  1871. X    NUMBER *r;
  1872. X
  1873. X    if (qisfrac(q))
  1874. X        error("Non-integral factorial");
  1875. X    r = qalloc();
  1876. X    zpfact(q->num, &r->num);
  1877. X    return r;
  1878. X}
  1879. X
  1880. X
  1881. X/*
  1882. X * Compute the lcm of all the numbers less than or equal to a number.
  1883. X *    q2 = qlcmfact(q1);
  1884. X */
  1885. XNUMBER *
  1886. Xqlcmfact(q)
  1887. X    register NUMBER *q;
  1888. X{
  1889. X    NUMBER *r;
  1890. X
  1891. X    if (qisfrac(q))
  1892. X        error("Non-integral lcmfact");
  1893. X    r = qalloc();
  1894. X    zlcmfact(q->num, &r->num);
  1895. X    return r;
  1896. X}
  1897. X
  1898. X
  1899. X/*
  1900. X * Compute the permutation function  M! / (M - N)!.
  1901. X */
  1902. XNUMBER *
  1903. Xqperm(q1, q2)
  1904. X    register NUMBER *q1, *q2;
  1905. X{
  1906. X    register NUMBER *r;
  1907. X
  1908. X    if (qisfrac(q1) || qisfrac(q2))
  1909. X        error("Non-integral arguments for permutation");
  1910. X    r = qalloc();
  1911. X    zperm(q1->num, q2->num, &r->num);
  1912. X    return r;
  1913. X}
  1914. X
  1915. X
  1916. X/*
  1917. X * Compute the combinatorial function  M! / (N! * (M - N)!).
  1918. X */
  1919. XNUMBER *
  1920. Xqcomb(q1, q2)
  1921. X    register NUMBER *q1, *q2;
  1922. X{
  1923. X    register NUMBER *r;
  1924. X
  1925. X    if (qisfrac(q1) || qisfrac(q2))
  1926. X        error("Non-integral arguments for combinatorial");
  1927. X    r = qalloc();
  1928. X    zcomb(q1->num, q2->num, &r->num);
  1929. X    return r;
  1930. X}
  1931. X
  1932. X
  1933. X/*
  1934. X * Compute the Jacobi function (a / b).
  1935. X * -1 => a is not quadratic residue mod b
  1936. X * 1 => b is composite, or a is quad residue of b
  1937. X * 0 => b is even or b < 0
  1938. X */
  1939. XNUMBER *
  1940. Xqjacobi(q1, q2)
  1941. X    register NUMBER *q1, *q2;
  1942. X{
  1943. X    if (qisfrac(q1) || qisfrac(q2))
  1944. X        error("Non-integral arguments for jacobi");
  1945. X    return itoq((long) zjacobi(q1->num, q2->num));
  1946. X}
  1947. X
  1948. X
  1949. X/*
  1950. X * Compute the Fibonacci number F(n).
  1951. X */
  1952. XNUMBER *
  1953. Xqfib(q)
  1954. X    register NUMBER *q;
  1955. X{
  1956. X    register NUMBER *r;
  1957. X
  1958. X    if (qisfrac(q))
  1959. X        error("Non-integral Fibonacci number");
  1960. X    r = qalloc();
  1961. X    zfib(q->num, &r->num);
  1962. X    return r;
  1963. X}
  1964. X
  1965. X
  1966. X/*
  1967. X * Truncate a number to the specified number of decimal places.
  1968. X * Specifying zero places makes the result identical to qint.
  1969. X * Example: qtrunc(2/3, 3) = .666
  1970. X */
  1971. XNUMBER *
  1972. Xqtrunc(q1, q2)
  1973. X    NUMBER *q1, *q2;
  1974. X{
  1975. X    long places;
  1976. X    NUMBER *r;
  1977. X    ZVALUE tenpow, tmp1, tmp2;
  1978. X
  1979. X    if (qisfrac(q2) || qisneg(q2) || !istiny(q2->num))
  1980. X        error("Bad number of places for qtrunc");
  1981. X    if (qisint(q1))
  1982. X        return qlink(q1);
  1983. X    r = qalloc();
  1984. X    places = z1tol(q2->num);
  1985. X    /*
  1986. X     * Ok, produce the result.
  1987. X     * First see if we want no places, in which case just take integer part.
  1988. X     */
  1989. X    if (places == 0) {
  1990. X        zquo(q1->num, q1->den, &r->num);
  1991. X        return r;
  1992. X    }
  1993. X    ztenpow(places, &tenpow);
  1994. X    zmul(q1->num, tenpow, &tmp1);
  1995. X    zquo(tmp1, q1->den, &tmp2);
  1996. X    freeh(tmp1.v);
  1997. X    if (iszero(tmp2)) {
  1998. X        freeh(tmp2.v);
  1999. X        return qlink(&_qzero_);
  2000. X    }
  2001. X    /*
  2002. X     * Now reduce the result to the lowest common denominator.
  2003. X     */
  2004. X    zgcd(tmp2, tenpow, &tmp1);
  2005. X    if (isunit(tmp1)) {
  2006. X        freeh(tmp1.v);
  2007. X        r->num = tmp2;
  2008. X        r->den = tenpow;
  2009. X        return r;
  2010. X    }
  2011. X    zquo(tmp2, tmp1, &r->num);
  2012. X    zquo(tenpow, tmp1, &r->den);
  2013. X    freeh(tmp1.v);
  2014. X    freeh(tmp2.v);
  2015. X    freeh(tenpow.v);
  2016. X    return r;
  2017. X}
  2018. X
  2019. X
  2020. X/*
  2021. X * Round a number to the specified number of decimal places.
  2022. X * Zero decimal places means round to the nearest integer.
  2023. X * Example: qround(2/3, 3) = .667
  2024. X */
  2025. XNUMBER *
  2026. Xqround(q, places)
  2027. X    NUMBER *q;        /* number to be rounded */
  2028. X    long places;        /* number of decimal places to round to */
  2029. X{
  2030. X    NUMBER *r;
  2031. X    ZVALUE tenpow, roundval, tmp1, tmp2;
  2032. X
  2033. X    if (places < 0)
  2034. X        error("Negative places for qround");
  2035. X    if (qisint(q))
  2036. X        return qlink(q);
  2037. X    /*
  2038. X     * Calculate one half of the denominator, ignoring fractional results.
  2039. X     * This is the value we will add in order to cause rounding.
  2040. X     */
  2041. X    zshift(q->den, -1L, &roundval);
  2042. X    roundval.sign = q->num.sign;
  2043. X    /*
  2044. X     * Ok, now do the actual work to produce the result.
  2045. X     */
  2046. X    r = qalloc();
  2047. X    ztenpow(places, &tenpow);
  2048. X    zmul(q->num, tenpow, &tmp2);
  2049. X    zadd(tmp2, roundval, &tmp1);
  2050. X    freeh(tmp2.v);
  2051. X    freeh(roundval.v);
  2052. X    zquo(tmp1, q->den, &tmp2);
  2053. X    freeh(tmp1.v);
  2054. X    if (iszero(tmp2)) {
  2055. X        freeh(tmp2.v);
  2056. X        return qlink(&_qzero_);
  2057. X    }
  2058. X    /*
  2059. X     * Now reduce the result to the lowest common denominator.
  2060. X     */
  2061. X    zgcd(tmp2, tenpow, &tmp1);
  2062. X    if (isunit(tmp1)) {
  2063. X        freeh(tmp1.v);
  2064. X        r->num = tmp2;
  2065. X        r->den = tenpow;
  2066. X        return r;
  2067. X    }
  2068. X    zquo(tmp2, tmp1, &r->num);
  2069. X    zquo(tenpow, tmp1, &r->den);
  2070. X    freeh(tmp1.v);
  2071. X    freeh(tmp2.v);
  2072. X    freeh(tenpow.v);
  2073. X    return r;
  2074. X}
  2075. X
  2076. X
  2077. X/*
  2078. X * Truncate a number to the specified number of binary places.
  2079. X * Specifying zero places makes the result identical to qint.
  2080. X */
  2081. XNUMBER *
  2082. Xqbtrunc(q1, q2)
  2083. X    NUMBER *q1, *q2;
  2084. X{
  2085. X    long places, twopow;
  2086. X    NUMBER *r;
  2087. X    ZVALUE tmp1, tmp2;
  2088. X
  2089. X    if (qisfrac(q2) || qisneg(q2) || !istiny(q2->num))
  2090. X        error("Bad number of places for qtrunc");
  2091. X    if (qisint(q1))
  2092. X        return qlink(q1);
  2093. X    r = qalloc();
  2094. X    places = z1tol(q2->num);
  2095. X    /*
  2096. X     * Ok, produce the result.
  2097. X     * First see if we want no places, in which case just take integer part.
  2098. X     */
  2099. X    if (places == 0) {
  2100. X        zquo(q1->num, q1->den, &r->num);
  2101. X        return r;
  2102. X    }
  2103. X    zshift(q1->num, places, &tmp1);
  2104. X    zquo(tmp1, q1->den, &tmp2);
  2105. X    freeh(tmp1.v);
  2106. X    if (iszero(tmp2)) {
  2107. X        freeh(tmp2.v);
  2108. X        return qlink(&_qzero_);
  2109. X    }
  2110. X    /*
  2111. X     * Now reduce the result to the lowest common denominator.
  2112. X     */
  2113. X    if (isodd(tmp2)) {
  2114. X        r->num = tmp2;
  2115. X        zbitvalue(places, &r->den);
  2116. X        return r;
  2117. X    }
  2118. X    twopow = zlowbit(tmp2);
  2119. X    if (twopow > places)
  2120. X        twopow = places;
  2121. X    places -= twopow;
  2122. X    zshift(tmp2, -twopow, &r->num);
  2123. X    freeh(tmp2.v);
  2124. X    zbitvalue(places, &r->den);
  2125. X    return r;
  2126. X}
  2127. X
  2128. X
  2129. X/*
  2130. X * Round a number to the specified number of binary places.
  2131. X * Zero binary places means round to the nearest integer.
  2132. X */
  2133. XNUMBER *
  2134. Xqbround(q, places)
  2135. X    NUMBER *q;        /* number to be rounded */
  2136. X    long places;        /* number of binary places to round to */
  2137. X{
  2138. X    long twopow;
  2139. X    NUMBER *r;
  2140. X    ZVALUE roundval, tmp1, tmp2;
  2141. X
  2142. X    if (places < 0)
  2143. X        error("Negative places for qbround");
  2144. X    if (qisint(q))
  2145. X        return qlink(q);
  2146. X    r = qalloc();
  2147. X    /*
  2148. X     * Calculate one half of the denominator, ignoring fractional results.
  2149. X     * This is the value we will add in order to cause rounding.
  2150. X     */
  2151. X    zshift(q->den, -1L, &roundval);
  2152. X    roundval.sign = q->num.sign;
  2153. X    /*
  2154. X     * Ok, produce the result.
  2155. X     */
  2156. X    zshift(q->num, places, &tmp1);
  2157. X    zadd(tmp1, roundval, &tmp2);
  2158. X    freeh(roundval.v);
  2159. X    freeh(tmp1.v);
  2160. X    zquo(tmp2, q->den, &tmp1);
  2161. X    freeh(tmp2.v);
  2162. X    if (iszero(tmp1)) {
  2163. X        freeh(tmp1.v);
  2164. X        return qlink(&_qzero_);
  2165. X    }
  2166. X    /*
  2167. X     * Now reduce the result to the lowest common denominator.
  2168. X     */
  2169. X    if (isodd(tmp1)) {
  2170. X        r->num = tmp1;
  2171. X        zbitvalue(places, &r->den);
  2172. X        return r;
  2173. X    }
  2174. X    twopow = zlowbit(tmp1);
  2175. X    if (twopow > places)
  2176. X        twopow = places;
  2177. X    places -= twopow;
  2178. X    zshift(tmp1, -twopow, &r->num);
  2179. X    freeh(tmp1.v);
  2180. X    zbitvalue(places, &r->den);
  2181. X    return r;
  2182. X}
  2183. X
  2184. X
  2185. X/*
  2186. X * Approximate a number by using binary rounding with the minimum number
  2187. X * of binary places so that the resulting number is within the specified
  2188. X * epsilon of the original number.
  2189. X */
  2190. XNUMBER *
  2191. Xqbappr(q, e)
  2192. X    NUMBER *q, *e;
  2193. X{
  2194. X    long bits;
  2195. X
  2196. X    if (qisneg(e) || qiszero(e))
  2197. X        error("Bad epsilon value for qbappr");
  2198. X    if (e == _epsilon_)
  2199. X        bits = _epsilonprec_ + 1;
  2200. X    else
  2201. X        bits = qprecision(e) + 1;
  2202. X    return qbround(q, bits);
  2203. X}
  2204. X
  2205. X
  2206. X/*
  2207. X * Approximate a number using continued fractions until the approximation
  2208. X * error is less than the specified value.  If a NULL pointer is given
  2209. X * for the error value, then the closest simpler fraction is returned.
  2210. X */
  2211. XNUMBER *
  2212. Xqcfappr(q, e)
  2213. X    NUMBER *q, *e;
  2214. X{
  2215. X    NUMBER qtest, *qtmp;
  2216. X    ZVALUE u1, u2, u3, v1, v2, v3, t1, t2, t3, qq, tt;
  2217. X    int i;
  2218. X    BOOL haveeps;
  2219. X
  2220. X    haveeps = TRUE;
  2221. X    if (e == NULL) {
  2222. X        haveeps = FALSE;
  2223. X        e = &_qzero_;
  2224. X    }
  2225. X    if (qisneg(e))
  2226. X        error("Negative epsilon for cfappr");
  2227. X    if (qisint(q) || isunit(q->num) || (haveeps && qiszero(e)))
  2228. X        return qlink(q);
  2229. X    u1 = _one_;
  2230. X    u2 = _zero_;
  2231. X    u3 = q->num;
  2232. X    u3.sign = 0;
  2233. X    v1 = _zero_;
  2234. X    v2 = _one_;
  2235. X    v3 = q->den;
  2236. X    while (!iszero(v3)) {
  2237. X        if (!iszero(u2) && !iszero(u1)) {
  2238. X            qtest.num = u2;
  2239. X            qtest.den = u1;
  2240. X            qtest.den.sign = 0;
  2241. X            qtest.num.sign = q->num.sign;
  2242. X            qtmp = qsub(q, &qtest);
  2243. X            qtest = *qtmp;
  2244. X            qtest.num.sign = 0;
  2245. X            i = qrel(&qtest, e);
  2246. X            qfree(qtmp);
  2247. X            if (i <= 0)
  2248. X                break;
  2249. X        }
  2250. X        zquo(u3, v3, &qq);
  2251. X        zmul(qq, v1, &tt); zsub(u1, tt, &t1); freeh(tt.v);
  2252. X        zmul(qq, v2, &tt); zsub(u2, tt, &t2); freeh(tt.v);
  2253. X        zmul(qq, v3, &tt); zsub(u3, tt, &t3); freeh(tt.v);
  2254. X        freeh(qq.v); freeh(u1.v); freeh(u2.v);
  2255. X        if ((u3.v != q->num.v) && (u3.v != q->den.v))
  2256. X            freeh(u3.v);
  2257. X        u1 = v1; u2 = v2; u3 = v3;
  2258. X        v1 = t1; v2 = t2; v3 = t3;
  2259. X    }
  2260. X    if (u3.v != q->den.v)
  2261. X        freeh(u3.v);
  2262. X    freeh(v1.v);
  2263. X    freeh(v2.v);
  2264. X    i = iszero(v3);
  2265. X    freeh(v3.v);
  2266. X    if (i && haveeps) {
  2267. X        freeh(u1.v);
  2268. X        freeh(u2.v);
  2269. X        return qlink(q);
  2270. X    }
  2271. X    qtest.num = u2;
  2272. X    qtest.den = u1;
  2273. X    qtest.den.sign = 0;
  2274. X    qtest.num.sign = q->num.sign;
  2275. X    qtmp = qcopy(&qtest);
  2276. X    freeh(u1.v);
  2277. X    freeh(u2.v);
  2278. X    return qtmp;
  2279. X}
  2280. X
  2281. X
  2282. X/*
  2283. X * Return an indication on whether or not two fractions are approximately
  2284. X * equal within the specified epsilon. Returns negative if the absolute value
  2285. X * of the difference between the two numbers is less than epsilon, zero if
  2286. X * the difference is equal to epsilon, and positive if the difference is
  2287. X * greater than epsilon.
  2288. X */
  2289. XFLAG
  2290. Xqnear(q1, q2, epsilon)
  2291. X    NUMBER *q1, *q2, *epsilon;
  2292. X{
  2293. X    int res;
  2294. X    NUMBER qtemp, *qq;
  2295. X
  2296. X    if (qisneg(epsilon))
  2297. X        error("Negative epsilon for near");
  2298. X    if (q1 == q2) {
  2299. X        if (qiszero(epsilon))
  2300. X            return 0;
  2301. X        return -1;
  2302. X    }
  2303. X    if (qiszero(epsilon))
  2304. X        return qcmp(q1, q2);
  2305. X    if (qiszero(q2)) {
  2306. X        qtemp = *q1;
  2307. X        qtemp.num.sign = 0;
  2308. X        return qrel(&qtemp, epsilon);
  2309. X    }
  2310. X    if (qiszero(q1)) {
  2311. X        qtemp = *q2;
  2312. X        qtemp.num.sign = 0;
  2313. X        return qrel(&qtemp, epsilon);
  2314. X    }
  2315. X    qq = qsub(q1, q2);
  2316. X    qtemp = *qq;
  2317. X    qtemp.num.sign = 0;
  2318. X    res = qrel(&qtemp, epsilon);
  2319. X    qfree(qq);
  2320. X    return res;
  2321. X}
  2322. X
  2323. X
  2324. X/*
  2325. X * Compute the gcd (greatest common divisor) of two numbers.
  2326. X *    q3 = qgcd(q1, q2);
  2327. X */
  2328. XNUMBER *
  2329. Xqgcd(q1, q2)
  2330. X    register NUMBER *q1, *q2;
  2331. X{
  2332. X    ZVALUE z;
  2333. X    NUMBER *q;
  2334. X
  2335. X    if (qisfrac(q1) || qisfrac(q2))
  2336. X        error("Non-integers for gcd");
  2337. X    zgcd(q1->num, q2->num, &z);
  2338. X    if (isunit(z)) {
  2339. X        freeh(z.v);
  2340. X        return qlink(&_qone_);
  2341. X    }
  2342. X    q = qalloc();
  2343. X    q->num = z;
  2344. X    return q;
  2345. X}
  2346. X
  2347. X
  2348. X/*
  2349. X * Compute the lcm (least common denominator) of two numbers.
  2350. X *    q3 = qlcm(q1, q2);
  2351. X */
  2352. XNUMBER *
  2353. Xqlcm(q1, q2)
  2354. X    register NUMBER *q1, *q2;
  2355. X{
  2356. X    NUMBER *q;
  2357. X
  2358. X    if (qisfrac(q1) || qisfrac(q2))
  2359. X        error("Non-integers for lcm");
  2360. X    if (qisunit(q1))
  2361. X        return qlink(q2);
  2362. X    if (qisunit(q2))
  2363. X        return qlink(q1);
  2364. X    q = qalloc();
  2365. X    zlcm(q1->num, q2->num, &q->num);
  2366. X    return q;
  2367. X}
  2368. X
  2369. X
  2370. X/*
  2371. X * Remove all occurances of the specified factor from a number.
  2372. X * Returned number is always positive.
  2373. X */
  2374. XNUMBER *
  2375. Xqfacrem(q1, q2)
  2376. X    NUMBER *q1, *q2;
  2377. X{
  2378. X    long count;
  2379. X    ZVALUE tmp;
  2380. X    NUMBER *r;
  2381. X
  2382. X    if (qisfrac(q1) || qisfrac(q2))
  2383. X        error("Non-integers for factor removal");
  2384. X    count = zfacrem(q1->num, q2->num, &tmp);
  2385. X    if (isunit(tmp)) {
  2386. X        freeh(tmp.v);
  2387. X        return qlink(&_qone_);
  2388. X    }
  2389. X    if (count == 0) {
  2390. X        freeh(tmp.v);
  2391. X        return qlink(q1);
  2392. X    }
  2393. X    r = qalloc();
  2394. X    r->num = tmp;
  2395. X    return r;
  2396. X}
  2397. X
  2398. X
  2399. X/*
  2400. X * Divide one number by the gcd of it with another number repeatedly until
  2401. X * the number is relatively prime.
  2402. X */
  2403. XNUMBER *
  2404. Xqgcdrem(q1, q2)
  2405. X    NUMBER *q1, *q2;
  2406. X{
  2407. X    ZVALUE tmp;
  2408. X    NUMBER *r;
  2409. X
  2410. X    if (qisfrac(q1) || qisfrac(q2))
  2411. X        error("Non-integers for gcdrem");
  2412. X    zgcdrem(q1->num, q2->num, &tmp);
  2413. X    if (isunit(tmp)) {
  2414. X        freeh(tmp.v);
  2415. X        return qlink(&_qone_);
  2416. X    }
  2417. X    if (zcmp(q1->num, tmp) == 0) {
  2418. X        freeh(tmp.v);
  2419. X        return qlink(q1);
  2420. X    }
  2421. X    r = qalloc();
  2422. X    r->num = tmp;
  2423. X    return r;
  2424. X}
  2425. X
  2426. X
  2427. X/*
  2428. X * Return the lowest prime factor of a number.
  2429. X * Search is conducted for the specified number of primes.
  2430. X * Returns one if no factor was found.
  2431. X */
  2432. XNUMBER *
  2433. Xqlowfactor(q1, q2)
  2434. X    NUMBER *q1, *q2;
  2435. X{
  2436. X    if (qisfrac(q1) || qisfrac(q2))
  2437. X        error("Non-integers for lowfactor");
  2438. X    return itoq(zlowfactor(q1->num, ztoi(q2->num)));
  2439. X}
  2440. X
  2441. X
  2442. X/*
  2443. X * Return the number of places after the decimal point needed to exactly
  2444. X * represent the specified number as a real number.  Integers return zero,
  2445. X * and non-terminating decimals return minus one.  Examples:
  2446. X *    qplaces(1/7)=-1, qplaces(3/10)= 1, qplaces(1/8)=3, qplaces(4)=0.
  2447. X */
  2448. Xlong
  2449. Xqplaces(q)
  2450. X    NUMBER *q;
  2451. X{
  2452. X    long twopow, fivepow;
  2453. X    HALF fiveval[2];
  2454. X    ZVALUE five;
  2455. X    ZVALUE tmp;
  2456. X
  2457. X    if (qisint(q))    /* no decimal places if number is integer */
  2458. X        return 0;
  2459. X    /*
  2460. X     * The number of decimal places of a fraction in lowest terms is finite
  2461. X     * if an only if the denominator is of the form 2^A * 5^B, and then the
  2462. X     * number of decimal places is equal to MAX(A, B).
  2463. X     */
  2464. X    five.sign = 0;
  2465. X    five.len = 1;
  2466. X    five.v = fiveval;
  2467. X    fiveval[0] = 5;
  2468. X    fivepow = zfacrem(q->den, five, &tmp);
  2469. X    if (!zisonebit(tmp)) {
  2470. X        freeh(tmp.v);
  2471. X        return -1;
  2472. X    }
  2473. X    twopow = zlowbit(tmp);
  2474. X    freeh(tmp.v);
  2475. X    if (twopow < fivepow)
  2476. X        twopow = fivepow;
  2477. X    return twopow;
  2478. X}
  2479. X
  2480. X
  2481. X/*
  2482. X * Perform a probabilistic primality test (algorithm P in Knuth).
  2483. X * Returns FALSE if definitely not prime, or TRUE if probably prime.
  2484. X * Second arg determines how many times to check for primality.
  2485. X */
  2486. XBOOL
  2487. Xqprimetest(q1, q2)
  2488. X    NUMBER *q1, *q2;
  2489. X{
  2490. X    if (qisfrac(q1) || qisfrac(q2) || qisneg(q2))
  2491. X        error("Bad arguments for qprimetest");
  2492. X    return zprimetest(q1->num, qtoi(q2));
  2493. X}
  2494. X
  2495. X/* END CODE */
  2496. END_OF_FILE
  2497. if test 24256 -ne `wc -c <'qfunc.c'`; then
  2498.     echo shar: \"'qfunc.c'\" unpacked with wrong size!
  2499. fi
  2500. # end of 'qfunc.c'
  2501. fi
  2502. echo shar: End of archive 10 \(of 21\).
  2503. cp /dev/null ark10isdone
  2504. MISSING=""
  2505. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ; do
  2506.     if test ! -f ark${I}isdone ; then
  2507.     MISSING="${MISSING} ${I}"
  2508.     fi
  2509. done
  2510. if test "${MISSING}" = "" ; then
  2511.     echo You have unpacked all 21 archives.
  2512.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  2513. else
  2514.     echo You still need to unpack the following archives:
  2515.     echo "        " ${MISSING}
  2516. fi
  2517. ##  End of shell archive.
  2518. exit 0
  2519.