3 SPDX-License-Identifier: BSD-2-Clause
5 Copyright (c) 2018-2020 Gavin D. Howard and contributors.
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
33 bcl - library of arbitrary precision decimal arithmetic
45 This procedure will allow clients to use signals to interrupt computations
48 **void bcl_handleSignal(***void***);**
50 **bool bcl_running(***void***);**
54 These items allow clients to set up bcl(3).
56 **BclError bcl_init(***void***);**
58 **void bcl_free(***void***);**
60 **bool bcl_abortOnFatalError(***void***);**
62 **void bcl_setAbortOnFatalError(bool** *abrt***);**
64 **void bcl_gc(***void***);**
68 These items will allow clients to handle contexts, which are isolated from each
69 other. This allows more than one client to use bcl(3) in the same program.
73 **typedef struct BclCtxt\* BclContext;**
75 **BclContext bcl_ctxt_create(***void***);**
77 **void bcl_ctxt_free(BclContext** *ctxt***);**
79 **BclError bcl_pushContext(BclContext** *ctxt***);**
81 **void bcl_popContext(***void***);**
83 **BclContext bcl_context(***void***);**
85 **void bcl_ctxt_freeNums(BclContext** *ctxt***);**
87 **size_t bcl_ctxt_scale(BclContext** *ctxt***);**
89 **void bcl_ctxt_setScale(BclContext** *ctxt***, size_t** *scale***);**
91 **size_t bcl_ctxt_ibase(BclContext** *ctxt***);**
93 **void bcl_ctxt_setIbase(BclContext** *ctxt***, size_t** *ibase***);**
95 **size_t bcl_ctxt_obase(BclContext** *ctxt***);**
97 **void bcl_ctxt_setObase(BclContext** *ctxt***, size_t** *obase***);**
101 These items allow clients to handle errors.
103 **typedef enum BclError BclError;**
105 **BclError bcl_err(BclNumber** *n***);**
109 These items allow clients to manipulate and query the arbitrary-precision
110 numbers managed by bcl(3).
112 **typedef struct { size_t i; } BclNumber;**
114 **BclNumber bcl_num_create(***void***);**
116 **void bcl_num_free(BclNumber** *n***);**
118 **bool bcl_num_neg(BclNumber** *n***);**
120 **void bcl_num_setNeg(BclNumber** *n***, bool** *neg***);**
122 **size_t bcl_num_scale(BclNumber** *n***);**
124 **BclError bcl_num_setScale(BclNumber** *n***, size_t** *scale***);**
126 **size_t bcl_num_len(BclNumber** *n***);**
130 These items allow clients to convert numbers into and from strings and integers.
132 **BclNumber bcl_parse(const char \*restrict** *val***);**
134 **char\* bcl_string(BclNumber** *n***);**
136 **BclError bcl_bigdig(BclNumber** *n***, BclBigDig \****result***);**
138 **BclNumber bcl_bigdig2num(BclBigDig** *val***);**
142 These items allow clients to run math on numbers.
144 **BclNumber bcl_add(BclNumber** *a***, BclNumber** *b***);**
146 **BclNumber bcl_sub(BclNumber** *a***, BclNumber** *b***);**
148 **BclNumber bcl_mul(BclNumber** *a***, BclNumber** *b***);**
150 **BclNumber bcl_div(BclNumber** *a***, BclNumber** *b***);**
152 **BclNumber bcl_mod(BclNumber** *a***, BclNumber** *b***);**
154 **BclNumber bcl_pow(BclNumber** *a***, BclNumber** *b***);**
156 **BclNumber bcl_lshift(BclNumber** *a***, BclNumber** *b***);**
158 **BclNumber bcl_rshift(BclNumber** *a***, BclNumber** *b***);**
160 **BclNumber bcl_sqrt(BclNumber** *a***);**
162 **BclError bcl_divmod(BclNumber** *a***, BclNumber** *b***, BclNumber \****c***, BclNumber \****d***);**
164 **BclNumber bcl_modexp(BclNumber** *a***, BclNumber** *b***, BclNumber** *c***);**
168 These items are miscellaneous.
170 **void bcl_zero(BclNumber** *n***);**
172 **void bcl_one(BclNumber** *n***);**
174 **ssize_t bcl_cmp(BclNumber** *a***, BclNumber** *b***);**
176 **BclError bcl_copy(BclNumber** *d***, BclNumber** *s***);**
178 **BclNumber bcl_dup(BclNumber** *s***);**
180 ## Pseudo-Random Number Generator
182 These items allow clients to manipulate the seeded pseudo-random number
185 **#define BCL_SEED_ULONGS**
187 **#define BCL_SEED_SIZE**
189 **typedef unsigned long BclBigDig;**
191 **typedef unsigned long BclRandInt;**
193 **BclNumber bcl_irand(BclNumber** *a***);**
195 **BclNumber bcl_frand(size_t** *places***);**
197 **BclNumber bcl_ifrand(BclNumber** *a***, size_t** *places***);**
199 **BclError bcl_rand_seedWithNum(BclNumber** *n***);**
201 **BclError bcl_rand_seed(unsigned char** *seed***[***BC_SEED_SIZE***]);**
203 **void bcl_rand_reseed(***void***);**
205 **BclNumber bcl_rand_seed2num(***void***);**
207 **BclRandInt bcl_rand_int(***void***);**
209 **BclRandInt bcl_rand_bounded(BclRandInt** *bound***);**
213 bcl(3) is a library that implements arbitrary-precision decimal math, as
214 [standardized by POSIX][1] in bc(1).
216 bcl(3) is async-signal-safe if **bcl_handleSignal(***void***)** is used
217 properly. (See the **SIGNAL HANDLING** section.)
219 All of the items in its interface are described below. See the documentation for
220 each function for what each function can return.
224 **void bcl_handleSignal(***void***)**
226 : An async-signal-safe function that can be called from a signal handler. If
227 called from a signal handler on the same thread as any executing bcl(3)
228 functions, it will interrupt the functions and force them to return early.
229 It is undefined behavior if this function is called from a thread that is
230 *not* executing any bcl(3) functions while any bcl(3) functions are
233 If execution *is* interrupted, **bcl_handleSignal(***void***)** does *not*
234 return to its caller.
236 See the **SIGNAL HANDLING** section.
238 **bool bcl_running(***void***)**
240 : An async-signal-safe function that can be called from a signal handler. It
241 will return **true** if any bcl(3) procedures are running, which means it is
242 safe to call **bcl_handleSignal(***void***)**. Otherwise, it returns
245 See the **SIGNAL HANDLING** section.
249 **BclError bcl_init(***void***)**
251 : Initializes this library. This function can be called multiple times, but
252 each call must be matched by a call to **bcl_free(***void***)**. This is to
253 make it possible for multiple libraries and applications to initialize
254 bcl(3) without problem.
256 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
259 * **BCL_ERROR_FATAL_ALLOC_ERR**
261 This function must be the first one clients call. Calling any other
262 function without calling this one first is undefined behavior.
264 **void bcl_free(***void***)**
266 : Decrements bcl(3)'s reference count and frees the data associated with it if
267 the reference count is **0**.
269 This function must be the last one clients call. Calling this function
270 before calling any other function is undefined behavior.
272 **bool bcl_abortOnFatalError(***void***)**
274 : Queries and returns the current state of calling **abort()** on fatal
275 errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
278 If activated, clients do not need to check for fatal errors.
280 **void bcl_setAbortOnFatalError(bool** *abrt***)**
282 : Sets the state of calling **abort()** on fatal errors. If *abrt* is
283 **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
284 call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
287 If activated, clients do not need to check for fatal errors.
289 **void bcl_gc(***void***)**
291 : Garbage collects cached instances of arbitrary-precision numbers. This only
292 frees the memory of numbers that are *not* in use, so it is safe to call at
297 All procedures that take a **BclContext** parameter a require a valid context as
302 : A forward declaration for a hidden **struct** type. Clients cannot access
303 the internals of the **struct** type directly. All interactions with the
304 type are done through pointers. See **BclContext** below.
308 : A typedef to a pointer of **struct BclCtxt**. This is the only handle
309 clients can get to **struct BclCtxt**.
311 A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
312 well as a list of numbers.
314 **scale** is a value used to control how many decimal places calculations
315 should use. A value of **0** means that calculations are done on integers
316 only, where applicable, and a value of 20, for example, means that all
317 applicable calculations return results with 20 decimal places. The default
320 **ibase** is a value used to control the input base. The minimum **ibase**
321 is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
322 parsed as though they are in binary, and any digits larger than **1** are
323 clamped. Likewise, a value of **10** means that numbers are parsed as though
324 they are decimal, and any larger digits are clamped. The default is **10**.
326 **obase** is a value used to control the output base. The minimum **obase**
327 is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
329 Numbers created in one context are not valid in another context. It is
330 undefined behavior to use a number created in a different context. Contexts
331 are meant to isolate the numbers used by different clients in the same
334 **BclContext bcl_ctxt_create(***void***)**
336 : Creates a context and returns it. Returns **NULL** if there was an error.
338 **void bcl_ctxt_free(BclContext** *ctxt***)**
340 : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
341 attempt to use an invalid context.
343 **BclError bcl_pushContext(BclContext** *ctxt***)**
345 : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
346 with **bcl_ctxt_create(***void***)**.
348 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
351 * **BCL_ERROR_FATAL_ALLOC_ERR**
353 There *must* be a valid context to do any arithmetic.
355 **void bcl_popContext(***void***)**
357 : Pops the current context off of the stack, if one exists.
359 **BclContext bcl_context(***void***)**
361 : Returns the current context, or **NULL** if no context exists.
363 **void bcl_ctxt_freeNums(BclContext** *ctxt***)**
365 : Frees all numbers in use that are associated with *ctxt*. It is undefined
366 behavior to attempt to use a number associated with *ctxt* after calling
367 this procedure unless such numbers have been created with
368 **bcl_num_create(***void***)** after calling this procedure.
370 **size_t bcl_ctxt_scale(BclContext** *ctxt***)**
372 : Returns the **scale** for given context.
374 **void bcl_ctxt_setScale(BclContext** *ctxt***, size_t** *scale***)**
376 : Sets the **scale** for the given context to the argument *scale*.
378 **size_t bcl_ctxt_ibase(BclContext** *ctxt***)**
380 : Returns the **ibase** for the given context.
382 **void bcl_ctxt_setIbase(BclContext** *ctxt***, size_t** *ibase***)**
384 : Sets the **ibase** for the given context to the argument *ibase*. If the
385 argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
386 clamped to **2**, and any values above **36** are clamped to **36**.
388 **size_t bcl_ctxt_obase(BclContext** *ctxt***)**
390 : Returns the **obase** for the given context.
392 **void bcl_ctxt_setObase(BclContext** *ctxt***, size_t** *obase***)**
394 : Sets the **obase** for the given context to the argument *obase*.
400 : An **enum** of possible error codes. See the **ERRORS** section for a
401 complete listing the codes.
403 **BclError bcl_err(BclNumber** *n***)**
405 : Checks for errors in a **BclNumber**. All functions that can return a
406 **BclNumber** can encode an error in the number, and this function will
407 return the error, if any. If there was no error, it will return
410 There must be a valid current context.
414 All procedures in this section require a valid current context.
418 : A handle to an arbitrary-precision number. The actual number type is not
419 exposed; the **BclNumber** handle is the only way clients can refer to
420 instances of arbitrary-precision numbers.
422 **BclNumber bcl_num_create(***void***)**
424 : Creates and returns a **BclNumber**.
426 bcl(3) will encode an error in the return value, if there was one. The error
427 can be queried with **bcl_err(BclNumber)**. Possible errors include:
429 * **BCL_ERROR_INVALID_CONTEXT**
430 * **BCL_ERROR_FATAL_ALLOC_ERR**
432 **void bcl_num_free(BclNumber** *n***)**
434 : Frees *n*. It is undefined behavior to use *n* after calling this function.
436 **bool bcl_num_neg(BclNumber** *n***)**
438 : Returns **true** if *n* is negative, **false** otherwise.
440 **void bcl_num_setNeg(BclNumber** *n***, bool** *neg***)**
442 : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
445 **size_t bcl_num_scale(BclNumber** *n***)**
447 : Returns the *scale* of *n*.
449 The *scale* of a number is the number of decimal places it has after the
450 radix (decimal point).
452 **BclError bcl_num_setScale(BclNumber** *n***, size_t** *scale***)**
454 : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
455 greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
456 less than the *scale* of *n*, *n* is truncated.
458 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
461 * **BCL_ERROR_INVALID_NUM**
462 * **BCL_ERROR_INVALID_CONTEXT**
463 * **BCL_ERROR_FATAL_ALLOC_ERR**
465 **size_t bcl_num_len(BclNumber** *n***)**
467 : Returns the number of *significant decimal digits* in *n*.
471 All procedures in this section require a valid current context.
473 All procedures in this section consume the given **BclNumber** arguments that
474 are not given to pointer arguments. See the **Consumption and Propagation**
477 **BclNumber bcl_parse(const char \*restrict** *val***)**
479 : Parses a number string according to the current context's **ibase** and
480 returns the resulting number.
482 *val* must be non-**NULL** and a valid string. See
483 **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
486 bcl(3) will encode an error in the return value, if there was one. The error
487 can be queried with **bcl_err(BclNumber)**. Possible errors include:
489 * **BCL_ERROR_INVALID_NUM**
490 * **BCL_ERROR_INVALID_CONTEXT**
491 * **BCL_ERROR_PARSE_INVALID_STR**
492 * **BCL_ERROR_FATAL_ALLOC_ERR**
494 **char\* bcl_string(BclNumber** *n***)**
496 : Returns a string representation of *n* according the the current context's
497 **ibase**. The string is dynamically allocated and must be freed by the
500 *n* is consumed; it cannot be used after the call. See the
501 **Consumption and Propagation** subsection below.
503 **BclError bcl_bigdig(BclNumber** *n***, BclBigDig \****result***)**
505 : Converts *n* into a **BclBigDig** and returns the result in the space
506 pointed to by *result*.
508 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
510 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
513 * **BCL_ERROR_INVALID_NUM**
514 * **BCL_ERROR_INVALID_CONTEXT**
515 * **BCL_ERROR_MATH_OVERFLOW**
517 *n* is consumed; it cannot be used after the call. See the
518 **Consumption and Propagation** subsection below.
520 **BclNumber bcl_bigdig2num(BclBigDig** *val***)**
522 : Creates a **BclNumber** from *val*.
524 bcl(3) will encode an error in the return value, if there was one. The error
525 can be queried with **bcl_err(BclNumber)**. Possible errors include:
527 * **BCL_ERROR_INVALID_CONTEXT**
528 * **BCL_ERROR_FATAL_ALLOC_ERR**
532 All procedures in this section require a valid current context.
534 All procedures in this section can return the following errors:
536 * **BCL_ERROR_INVALID_NUM**
537 * **BCL_ERROR_INVALID_CONTEXT**
538 * **BCL_ERROR_FATAL_ALLOC_ERR**
540 **BclNumber bcl_add(BclNumber** *a***, BclNumber** *b***)**
542 : Adds *a* and *b* and returns the result. The *scale* of the result is the
543 max of the *scale*s of *a* and *b*.
545 *a* and *b* are consumed; they cannot be used after the call. See the
546 **Consumption and Propagation** subsection below.
548 *a* and *b* can be the same number.
550 bcl(3) will encode an error in the return value, if there was one. The error
551 can be queried with **bcl_err(BclNumber)**. Possible errors include:
553 * **BCL_ERROR_INVALID_NUM**
554 * **BCL_ERROR_INVALID_CONTEXT**
555 * **BCL_ERROR_FATAL_ALLOC_ERR**
557 **BclNumber bcl_sub(BclNumber** *a***, BclNumber** *b***)**
559 : Subtracts *b* from *a* and returns the result. The *scale* of the result is
560 the max of the *scale*s of *a* and *b*.
562 *a* and *b* are consumed; they cannot be used after the call. See the
563 **Consumption and Propagation** subsection below.
565 *a* and *b* can be the same number.
567 bcl(3) will encode an error in the return value, if there was one. The error
568 can be queried with **bcl_err(BclNumber)**. Possible errors include:
570 * **BCL_ERROR_INVALID_NUM**
571 * **BCL_ERROR_INVALID_CONTEXT**
572 * **BCL_ERROR_FATAL_ALLOC_ERR**
574 **BclNumber bcl_mul(BclNumber** *a***, BclNumber** *b***)**
576 : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
577 *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
578 to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
579 **max()** return the obvious values.
581 *a* and *b* are consumed; they cannot be used after the call. See the
582 **Consumption and Propagation** subsection below.
584 *a* and *b* can be the same number.
586 bcl(3) will encode an error in the return value, if there was one. The error
587 can be queried with **bcl_err(BclNumber)**. Possible errors include:
589 * **BCL_ERROR_INVALID_NUM**
590 * **BCL_ERROR_INVALID_CONTEXT**
591 * **BCL_ERROR_FATAL_ALLOC_ERR**
593 **BclNumber bcl_div(BclNumber** *a***, BclNumber** *b***)**
595 : Divides *a* by *b* and returns the result. The *scale* of the result is the
596 *scale* of the current context.
600 *a* and *b* are consumed; they cannot be used after the call. See the
601 **Consumption and Propagation** subsection below.
603 *a* and *b* can be the same number.
605 bcl(3) will encode an error in the return value, if there was one. The error
606 can be queried with **bcl_err(BclNumber)**. Possible errors include:
608 * **BCL_ERROR_INVALID_NUM**
609 * **BCL_ERROR_INVALID_CONTEXT**
610 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
611 * **BCL_ERROR_FATAL_ALLOC_ERR**
613 **BclNumber bcl_mod(BclNumber** *a***, BclNumber** *b***)**
615 : Divides *a* by *b* to the *scale* of the current context, computes the
616 modulus **a-(a/b)\*b**, and returns the modulus.
620 *a* and *b* are consumed; they cannot be used after the call. See the
621 **Consumption and Propagation** subsection below.
623 *a* and *b* can be the same number.
625 bcl(3) will encode an error in the return value, if there was one. The error
626 can be queried with **bcl_err(BclNumber)**. Possible errors include:
628 * **BCL_ERROR_INVALID_NUM**
629 * **BCL_ERROR_INVALID_CONTEXT**
630 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
631 * **BCL_ERROR_FATAL_ALLOC_ERR**
633 **BclNumber bcl_pow(BclNumber** *a***, BclNumber** *b***)**
635 : Calculates *a* to the power of *b* to the *scale* of the current context.
636 *b* must be an integer, but can be negative. If it is negative, *a* must
639 *b* must be an integer. If *b* is negative, *a* must not be **0**.
641 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
643 *a* and *b* are consumed; they cannot be used after the call. See the
644 **Consumption and Propagation** subsection below.
646 *a* and *b* can be the same number.
648 bcl(3) will encode an error in the return value, if there was one. The error
649 can be queried with **bcl_err(BclNumber)**. Possible errors include:
651 * **BCL_ERROR_INVALID_NUM**
652 * **BCL_ERROR_INVALID_CONTEXT**
653 * **BCL_ERROR_MATH_NON_INTEGER**
654 * **BCL_ERROR_MATH_OVERFLOW**
655 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
656 * **BCL_ERROR_FATAL_ALLOC_ERR**
658 **BclNumber bcl_lshift(BclNumber** *a***, BclNumber** *b***)**
660 : Shifts *a* left (moves the radix right) by *b* places and returns the
661 result. This is done in decimal. *b* must be an integer.
663 *b* must be an integer.
665 *a* and *b* are consumed; they cannot be used after the call. See the
666 **Consumption and Propagation** subsection below.
668 *a* and *b* can be the same number.
670 bcl(3) will encode an error in the return value, if there was one. The error
671 can be queried with **bcl_err(BclNumber)**. Possible errors include:
673 * **BCL_ERROR_INVALID_NUM**
674 * **BCL_ERROR_INVALID_CONTEXT**
675 * **BCL_ERROR_MATH_NON_INTEGER**
676 * **BCL_ERROR_FATAL_ALLOC_ERR**
678 **BclNumber bcl_rshift(BclNumber** *a***, BclNumber** *b***)**
680 : Shifts *a* right (moves the radix left) by *b* places and returns the
681 result. This is done in decimal. *b* must be an integer.
683 *b* must be an integer.
685 *a* and *b* are consumed; they cannot be used after the call. See the
686 **Consumption and Propagation** subsection below.
688 *a* and *b* can be the same number.
690 bcl(3) will encode an error in the return value, if there was one. The error
691 can be queried with **bcl_err(BclNumber)**. Possible errors include:
693 * **BCL_ERROR_INVALID_NUM**
694 * **BCL_ERROR_INVALID_CONTEXT**
695 * **BCL_ERROR_MATH_NON_INTEGER**
696 * **BCL_ERROR_FATAL_ALLOC_ERR**
698 **BclNumber bcl_sqrt(BclNumber** *a***)**
700 : Calculates the square root of *a* and returns the result. The *scale* of the
701 result is equal to the **scale** of the current context.
703 *a* cannot be negative.
705 *a* is consumed; it cannot be used after the call. See the
706 **Consumption and Propagation** subsection below.
708 bcl(3) will encode an error in the return value, if there was one. The error
709 can be queried with **bcl_err(BclNumber)**. Possible errors include:
711 * **BCL_ERROR_INVALID_NUM**
712 * **BCL_ERROR_INVALID_CONTEXT**
713 * **BCL_ERROR_MATH_NEGATIVE**
714 * **BCL_ERROR_FATAL_ALLOC_ERR**
716 **BclError bcl_divmod(BclNumber** *a***, BclNumber** *b***, BclNumber \****c***, BclNumber \****d***)**
718 : Divides *a* by *b* and returns the quotient in a new number which is put
719 into the space pointed to by *c*, and puts the modulus in a new number which
720 is put into the space pointed to by *d*.
724 *a* and *b* are consumed; they cannot be used after the call. See the
725 **Consumption and Propagation** subsection below.
727 *c* and *d* cannot point to the same place, nor can they point to the space
728 occupied by *a* or *b*.
730 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
733 * **BCL_ERROR_INVALID_NUM**
734 * **BCL_ERROR_INVALID_CONTEXT**
735 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
736 * **BCL_ERROR_FATAL_ALLOC_ERR**
738 **BclNumber bcl_modexp(BclNumber** *a***, BclNumber** *b***, BclNumber** *c***)**
740 : Computes a modular exponentiation where *a* is the base, *b* is the
741 exponent, and *c* is the modulus, and returns the result. The *scale* of the
742 result is equal to the **scale** of the current context.
744 *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
747 *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
748 **Consumption and Propagation** subsection below.
750 bcl(3) will encode an error in the return value, if there was one. The error
751 can be queried with **bcl_err(BclNumber)**. Possible errors include:
753 * **BCL_ERROR_INVALID_NUM**
754 * **BCL_ERROR_INVALID_CONTEXT**
755 * **BCL_ERROR_MATH_NEGATIVE**
756 * **BCL_ERROR_MATH_NON_INTEGER**
757 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
758 * **BCL_ERROR_FATAL_ALLOC_ERR**
762 **void bcl_zero(BclNumber** *n***)**
766 **void bcl_one(BclNumber** *n***)**
770 **ssize_t bcl_cmp(BclNumber** *a***, BclNumber** *b***)**
772 : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
773 *a* is less than *b*, and **>0** if *a* is greater than *b*.
775 **BclError bcl_copy(BclNumber** *d***, BclNumber** *s***)**
777 : Copies *s* into *d*.
779 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
782 * **BCL_ERROR_INVALID_NUM**
783 * **BCL_ERROR_INVALID_CONTEXT**
784 * **BCL_ERROR_FATAL_ALLOC_ERR**
786 **BclNumber bcl_dup(BclNumber** *s***)**
788 : Creates and returns a new **BclNumber** that is a copy of *s*.
790 bcl(3) will encode an error in the return value, if there was one. The error
791 can be queried with **bcl_err(BclNumber)**. Possible errors include:
793 * **BCL_ERROR_INVALID_NUM**
794 * **BCL_ERROR_INVALID_CONTEXT**
795 * **BCL_ERROR_FATAL_ALLOC_ERR**
797 ## Pseudo-Random Number Generator
799 The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
800 seed twice, it will produce the same sequence of pseudo-random numbers twice.
802 By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
803 that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
804 then calling **rand()** for each byte, since **rand()** is only guaranteed to
807 This should provide fairly good seeding in the standard case while also
808 remaining fairly portable.
810 If necessary, the PRNG can be reseeded with one of the following functions:
812 * **bcl_rand_seedWithNum(BclNumber)**
813 * **bcl_rand_seed(unsigned char[BC_SEED_SIZE])**
814 * **bcl_rand_reseed(***void***)**
816 The following items allow clients to use the pseudo-random number generator. All
817 procedures require a valid current context.
821 : The number of **unsigned long**'s in a seed for bcl(3)'s random number
826 : The size, in **char**'s, of a seed for bcl(3)'s random number generator.
830 : bcl(3)'s overflow type (see the **PERFORMANCE** section).
834 : An unsigned integer type returned by bcl(3)'s random number generator.
836 **BclNumber bcl_irand(BclNumber** *a***)**
838 : Returns a random number that is not larger than *a* in a new number. If *a*
839 is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
840 so it is not bound to the size of **BclRandInt**. This is done by generating
841 as many random numbers as necessary, multiplying them by certain exponents,
842 and adding them all together.
844 *a* must be an integer and non-negative.
846 *a* is consumed; it cannot be used after the call. See the
847 **Consumption and Propagation** subsection below.
849 This procedure requires a valid current context.
851 bcl(3) will encode an error in the return value, if there was one. The error
852 can be queried with **bcl_err(BclNumber)**. Possible errors include:
854 * **BCL_ERROR_INVALID_NUM**
855 * **BCL_ERROR_INVALID_CONTEXT**
856 * **BCL_ERROR_MATH_NEGATIVE**
857 * **BCL_ERROR_MATH_NON_INTEGER**
858 * **BCL_ERROR_FATAL_ALLOC_ERR**
860 **BclNumber bcl_frand(size_t** *places***)**
862 : Returns a random number between **0** (inclusive) and **1** (exclusive) that
863 has *places* decimal digits after the radix (decimal point). There are no
866 This procedure requires a valid current context.
868 bcl(3) will encode an error in the return value, if there was one. The error
869 can be queried with **bcl_err(BclNumber)**. Possible errors include:
871 * **BCL_ERROR_INVALID_CONTEXT**
872 * **BCL_ERROR_FATAL_ALLOC_ERR**
874 **BclNumber bcl_ifrand(BclNumber** *a***, size_t** *places***)**
876 : Returns a random number less than *a* with *places* decimal digits after the
877 radix (decimal point). There are no limits on *a* or *places*.
879 *a* must be an integer and non-negative.
881 *a* is consumed; it cannot be used after the call. See the
882 **Consumption and Propagation** subsection below.
884 This procedure requires a valid current context.
886 bcl(3) will encode an error in the return value, if there was one. The error
887 can be queried with **bcl_err(BclNumber)**. Possible errors include:
889 * **BCL_ERROR_INVALID_NUM**
890 * **BCL_ERROR_INVALID_CONTEXT**
891 * **BCL_ERROR_MATH_NEGATIVE**
892 * **BCL_ERROR_MATH_NON_INTEGER**
893 * **BCL_ERROR_FATAL_ALLOC_ERR**
895 **BclError bcl_rand_seedWithNum(BclNumber** *n***)**
897 : Seeds the PRNG with *n*.
899 *n* is *not* consumed.
901 This procedure requires a valid current context.
903 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
906 * **BCL_ERROR_INVALID_NUM**
907 * **BCL_ERROR_INVALID_CONTEXT**
909 Note that if **bcl_rand_seed2num(***void***)** or
910 **bcl_rand_seed2num_err(BclNumber)** are called right after this function,
911 they are not guaranteed to return a number equal to *n*.
913 **BclError bcl_rand_seed(unsigned char** *seed***[***BC_SEED_SIZE***])**
915 : Seeds the PRNG with the bytes in *seed*.
917 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
920 * **BCL_ERROR_INVALID_CONTEXT**
922 **void bcl_rand_reseed(***void***)**
924 : Reseeds the PRNG with the default reseeding behavior. First, it attempts to
925 read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
927 This procedure cannot fail.
929 **BclNumber bcl_rand_seed2num(***void***)**
931 : Returns the current seed of the PRNG as a **BclNumber**.
933 This procedure requires a valid current context.
935 bcl(3) will encode an error in the return value, if there was one. The error
936 can be queried with **bcl_err(BclNumber)**. Possible errors include:
938 * **BCL_ERROR_INVALID_CONTEXT**
939 * **BCL_ERROR_FATAL_ALLOC_ERR**
941 **BclRandInt bcl_rand_int(***void***)**
943 : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
945 This procedure cannot fail.
947 **BclRandInt bcl_rand_bounded(BclRandInt** *bound***)**
949 : Returns a random integer between **0** and *bound* (exclusive). Bias is
950 removed before returning the integer.
952 This procedure cannot fail.
954 ## Consumption and Propagation
956 Some functions are listed as consuming some or all of their arguments. This
957 means that the arguments are freed, regardless of if there were errors or not.
959 This is to enable compact code like the following:
961 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
963 If arguments to those functions were not consumed, memory would be leaked until
964 reclaimed with **bcl_ctxt_freeNums(BclContext)**.
966 When errors occur, they are propagated through. The result should always be
967 checked with **bcl_err(BclNumber)**, so the example above should properly
970 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
971 if (bc_num_err(n) != BCL_ERROR_NONE) {
977 Most functions in bcl(3) return, directly or indirectly, any one of the error
978 codes defined in **BclError**. The complete list of codes is the following:
982 : Success; no error occurred.
984 **BCL_ERROR_INVALID_NUM**
986 : An invalid **BclNumber** was given as a parameter.
988 **BCL_ERROR_INVALID_CONTEXT**
990 : An invalid **BclContext** is being used.
994 : A signal interrupted execution.
996 **BCL_ERROR_MATH_NEGATIVE**
998 : A negative number was given as an argument to a parameter that cannot accept
999 negative numbers, such as for square roots.
1001 **BCL_ERROR_MATH_NON_INTEGER**
1003 : A non-integer was given as an argument to a parameter that cannot accept
1004 non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
1006 **BCL_ERROR_MATH_OVERFLOW**
1008 : A number that would overflow its result was given as an argument, such as
1009 for converting a **BclNumber** to a **BclBigDig**.
1011 **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1013 : A divide by zero occurred.
1015 **BCL_ERROR_PARSE_INVALID_STR**
1017 : An invalid number string was passed to a parsing function.
1019 A valid number string can only be one radix (period). In addition, any
1020 lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
1021 allowed for the first character to be a dash. In that case, the number is
1022 considered to be negative.
1024 There is one exception to the above: one lowercase **e** is allowed in the
1025 number, after the radix, if it exists. If the letter **e** exists, the
1026 number is considered to be in scientific notation, where the part before the
1027 **e** is the number, and the part after, which must be an integer, is the
1028 exponent. There can be a dash right after the **e** to indicate a negative
1031 **WARNING**: Both the number and the exponent in scientific notation are
1032 interpreted according to the current **ibase**, but the number is still
1033 multiplied by **10\^exponent** regardless of the current **ibase**. For
1034 example, if **ibase** is **16** and bcl(3) is given the number string
1035 **FFeA**, the resulting decimal number will be **2550000000000**, and if
1036 bcl(3) is given the number string **10e-4**, the resulting decimal number
1039 **BCL_ERROR_FATAL_ALLOC_ERR**
1041 : bcl(3) failed to allocate memory.
1043 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1044 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1045 be turned off later by calling that same function with a **false** argument.
1046 By default, this behavior is off.
1048 It is highly recommended that client libraries do *not* activate this
1051 **BCL_ERROR_FATAL_UNKNOWN_ERR**
1053 : An unknown error occurred.
1055 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1056 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1057 be turned off later by calling that same function with a **false** argument.
1058 By default, this behavior is off.
1060 It is highly recommended that client libraries do *not* activate this
1065 When **bcl_handleSignal(***void***)** is used properly, bcl(3) is
1068 bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
1073 Most bc(1) implementations use **char** types to calculate the value of **1**
1074 decimal digit at a time, but that can be slow. bcl(3) does something
1077 It uses large integers to calculate more than **1** decimal digit at a time. If
1078 built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1079 **64**, then each integer has **9** decimal digits. If built in an environment
1080 where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1081 value (the number of decimal digits per large integer) is called
1084 In addition, this bcl(3) uses an even larger integer for overflow checking. This
1085 integer type depends on the value of **BC_LONG_BIT**, but is always at least
1086 twice as large as the integer type used to store digits.
1090 The following are the limits on bcl(3):
1094 : The number of bits in the **long** type in the environment where bcl(3) was
1095 built. This determines how many decimal digits can be stored in a single
1096 large integer (see the **PERFORMANCE** section).
1100 : The number of decimal digits per large integer (see the **PERFORMANCE**
1101 section). Depends on **BC_LONG_BIT**.
1105 : The max decimal number that each large integer can store (see
1106 **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1110 : The max number that the overflow type (see the **PERFORMANCE** section) can
1111 hold. Depends on **BC_LONG_BIT**.
1115 : The maximum output base. Set at **BC_BASE_POW**.
1119 : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1123 : The maximum length of a number (in decimal digits), which includes digits
1124 after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1128 : The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1129 Set at **2\^BC_LONG_BIT-1**.
1133 : The maximum allowable exponent (positive or negative). Set at
1134 **BC_OVERFLOW_MAX**.
1136 These limits are meant to be effectively non-existent; the limits are so large
1137 (at least on 64-bit machines) that there should not be any point at which they
1138 become a problem. In fact, memory should be exhausted before these limits should
1143 If a signal handler calls **bcl_handleSignal(***void***)** from the same thread
1144 that there are bcl(3) functions executing in, it will cause all execution to
1145 stop as soon as possible, interrupting long-running calculations, if necessary
1146 and cause the function that was executing to return. If possible, the error code
1147 **BC_ERROR_SIGNAL** is returned.
1149 If execution *is* interrupted, **bcl_handleSignal(***void***)** does *not*
1150 return to its caller.
1152 It is undefined behavior if **bcl_handleSignal(***void***)** is called from
1153 a thread that is not executing bcl(3) functions, if bcl(3) functions are
1162 bcl(3) is compliant with the arithmetic defined in the
1163 [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification for bc(1).
1165 Note that the specification explicitly says that bc(1) only accepts numbers that
1166 use a period (**.**) as a radix point, regardless of the value of
1167 **LC_NUMERIC**. This is also true of bcl(3).
1171 None are known. Report bugs at https://git.yzena.com/gavin/bc.
1175 Gavin D. Howard <gavin@yzena.com> and contributors.
1177 [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html