3 SPDX-License-Identifier: BSD-2-Clause
5 Copyright (c) 2018-2023 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
41 Link with *-lbcl*, and on POSIX systems, *-lpthread* is also required.
45 These items allow clients to set up bcl(3).
47 **BclError bcl_start(**_void_**);**
49 **void bcl_end(**_void_**);**
51 **BclError bcl_init(**_void_**);**
53 **void bcl_free(**_void_**);**
55 **bool bcl_abortOnFatalError(**_void_**);**
57 **void bcl_setAbortOnFatalError(bool** _abrt_**);**
59 **bool bcl_leadingZeroes(**_void_**);**
61 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**);**
63 **void bcl_gc(**_void_**);**
65 **bool bcl_digitClamp(**_void_**);**
67 **void bcl_setDigitClamp(bool** _digitClamp_**);**
71 These items will allow clients to handle contexts, which are isolated from each
72 other. This allows more than one client to use bcl(3) in the same program.
76 **typedef struct BclCtxt\* BclContext;**
78 **BclContext bcl_ctxt_create(**_void_**);**
80 **void bcl_ctxt_free(BclContext** _ctxt_**);**
82 **BclError bcl_pushContext(BclContext** _ctxt_**);**
84 **void bcl_popContext(**_void_**);**
86 **BclContext bcl_context(**_void_**);**
88 **void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
90 **size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
92 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
94 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
96 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
98 **size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
100 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
104 These items allow clients to handle errors.
106 **typedef enum BclError BclError;**
108 **BclError bcl_err(BclNumber** _n_**);**
112 These items allow clients to manipulate and query the arbitrary-precision
113 numbers managed by bcl(3).
115 **typedef struct { size_t i; } BclNumber;**
117 **BclNumber bcl_num_create(**_void_**);**
119 **void bcl_num_free(BclNumber** _n_**);**
121 **bool bcl_num_neg(BclNumber** _n_**);**
123 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
125 **size_t bcl_num_scale(BclNumber** _n_**);**
127 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
129 **size_t bcl_num_len(BclNumber** _n_**);**
133 These items allow clients to convert numbers into and from strings and integers.
135 **BclNumber bcl_parse(const char \*restrict** _val_**);**
137 **char\* bcl_string(BclNumber** _n_**);**
139 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
141 **BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
145 These items allow clients to run math on numbers.
147 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
149 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
151 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
153 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
155 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
157 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
159 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
161 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
163 **BclNumber bcl_sqrt(BclNumber** _a_**);**
165 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
167 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
171 These items are miscellaneous.
173 **void bcl_zero(BclNumber** _n_**);**
175 **void bcl_one(BclNumber** _n_**);**
177 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
179 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
181 **BclNumber bcl_dup(BclNumber** _s_**);**
183 ## Pseudo-Random Number Generator
185 These items allow clients to manipulate the seeded pseudo-random number
188 **#define BCL_SEED_ULONGS**
190 **#define BCL_SEED_SIZE**
192 **typedef unsigned long BclBigDig;**
194 **typedef unsigned long BclRandInt;**
196 **BclNumber bcl_irand(BclNumber** _a_**);**
198 **BclNumber bcl_frand(size_t** _places_**);**
200 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
202 **BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
204 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
206 **void bcl_rand_reseed(**_void_**);**
208 **BclNumber bcl_rand_seed2num(**_void_**);**
210 **BclRandInt bcl_rand_int(**_void_**);**
212 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
216 bcl(3) is a library that implements arbitrary-precision decimal math, as
217 standardized by POSIX
218 (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1).
220 bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and
221 **Bc** prefixes for symbol names without collision.
223 All of the items in its interface are described below. See the documentation for
224 each function for what each function can return.
228 **BclError bcl_start(**_void_**)**
230 : Initializes this library. This function can be called multiple times, but
231 **bcl_end()** must only be called *once*. This is to make it possible for
232 multiple libraries and applications to initialize bcl(3) without problem.
234 It is suggested that client libraries call this function, but do not call
235 **bcl_end()**, and client applications should call both.
237 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
240 * **BCL_ERROR_FATAL_ALLOC_ERR**
242 This function must be the first one clients call. Calling any other
243 function without calling this one first is undefined behavior.
245 **void bcl_end(**_void_**)**
247 : Deinitializes this library. This function must only be called *once*.
249 All data must have been freed before calling this function.
251 This function must be the last one clients call. Calling this function
252 before calling any other function is undefined behavior.
254 **BclError bcl_init(**_void_**)**
256 : Initializes the library for the current thread. This function can be called
257 multiple times, but each call must be matched by a call to
258 **bcl_free(**_void_**)**. This is to make it possible for multiple libraries
259 and applications to initialize threads for bcl(3) without problem.
261 This function *must* be called from the thread that it is supposed to
264 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
267 * **BCL_ERROR_FATAL_ALLOC_ERR**
269 This function must be the second one clients call. Calling any other
270 function without calling **bcl_start()** and then this one first is
271 undefined behavior, except in the case of new threads. New threads can
272 safely call this function without calling **bcl_start()** if another thread
273 has previously called **bcl_start()**. But this function must still be the
274 first function in bcl(3) called by that new thread.
276 **void bcl_free(**_void_**)**
278 : Decrements bcl(3)'s reference count and frees the data associated with it if
279 the reference count is **0**.
281 This function *must* be called from the thread that it is supposed to
284 This function must be the second to last one clients call. Calling this
285 function before calling any other function besides **bcl_end()** is
288 **bool bcl_abortOnFatalError(**_void_**)**
290 : Queries and returns the current state of calling **abort()** on fatal
291 errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
294 If activated, clients do not need to check for fatal errors.
296 This value is *thread-local*; it applies to just the thread it is read on.
298 The default is **false**.
300 **void bcl_setAbortOnFatalError(bool** _abrt_**)**
302 : Sets the state of calling **abort()** on fatal errors. If *abrt* is
303 **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
304 call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
307 This value is *thread-local*; it applies to just the thread it is set on.
309 If activated, clients do not need to check for fatal errors.
311 **bool bcl_leadingZeroes(**_void_**)**
313 : Queries and returns the state of whether leading zeroes are added to strings
314 returned by **bcl_string()** when numbers are greater than **-1**, less than
315 **1**, and not equal to **0**. If **true** is returned, then leading zeroes
318 This value is *thread-local*; it applies to just the thread it is read on.
320 The default is **false**.
322 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**)**
324 : Sets the state of whether leading zeroes are added to strings returned by
325 **bcl_string()** when numbers are greater than **-1**, less than **1**, and
326 not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be
327 added to strings returned by **bcl_string()**.
329 This value is *thread-local*; it applies to just the thread it is set on.
331 **bool bcl_digitClamp(**_void_**)**
333 : Queries and returns the state of whether digits in number strings that are
334 greater than or equal to the current **ibase** are clamped or not.
336 If **true** is returned, then digits are treated as though they are equal to
337 the value of **ibase** minus **1**. If this is *not* true, then digits are
338 treated as though they are equal to the value they would have if **ibase**
339 was large enough. They are then multiplied by the appropriate power of
342 For example, with clamping off and an **ibase** of **3**, the string "AB"
343 would equal **3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or
344 **41**, while with clamping on and an **ibase** of **3**, the string "AB"
345 would be equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus
348 This value is *thread-local*; it applies to just the thread it is read on.
350 The default is **true**.
352 **void bcl_setDigitClamp(bool** _digitClamp_**)**
354 : Sets the state of whether digits in number strings that are greater than or
355 equal to the current **ibase** are clamped or not. For more information, see
356 the **bcl_digitClamp(**_void_**)** function.
358 This value is *thread-local*; it applies to just the thread it is set on.
360 **void bcl_gc(**_void_**)**
362 : Garbage collects cached instances of arbitrary-precision numbers. This only
363 frees the memory of numbers that are *not* in use, so it is safe to call at
368 All procedures that take a **BclContext** parameter a require a valid context as
373 : A forward declaration for a hidden **struct** type. Clients cannot access
374 the internals of the **struct** type directly. All interactions with the
375 type are done through pointers. See **BclContext** below.
379 : A typedef to a pointer of **struct BclCtxt**. This is the only handle
380 clients can get to **struct BclCtxt**.
382 A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
383 well as a list of numbers.
385 **scale** is a value used to control how many decimal places calculations
386 should use. A value of **0** means that calculations are done on integers
387 only, where applicable, and a value of 20, for example, means that all
388 applicable calculations return results with 20 decimal places. The default
391 **ibase** is a value used to control the input base. The minimum **ibase**
392 is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
393 parsed as though they are in binary, and any digits larger than **1** are
394 clamped. Likewise, a value of **10** means that numbers are parsed as though
395 they are decimal, and any larger digits are clamped. The default is **10**.
397 **obase** is a value used to control the output base. The minimum **obase**
398 is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
400 Numbers created in one context are not valid in another context. It is
401 undefined behavior to use a number created in a different context. Contexts
402 are meant to isolate the numbers used by different clients in the same
405 Different threads also have different contexts, so any numbers created in
406 one thread are not valid in another thread. To pass values between contexts
407 and threads, use **bcl_string()** to produce a string to pass around, and
408 use **bcl_parse()** to parse the string. It is suggested that the **obase**
409 used to create the string be passed around with the string and used as the
410 **ibase** for **bcl_parse()** to ensure that the number will be the same.
412 **BclContext bcl_ctxt_create(**_void_**)**
414 : Creates a context and returns it. Returns **NULL** if there was an error.
416 **void bcl_ctxt_free(BclContext** _ctxt_**)**
418 : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
419 attempt to use an invalid context.
421 **BclError bcl_pushContext(BclContext** _ctxt_**)**
423 : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
424 with **bcl_ctxt_create(**_void_**)**.
426 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
429 * **BCL_ERROR_FATAL_ALLOC_ERR**
431 There *must* be a valid context to do any arithmetic.
433 **void bcl_popContext(**_void_**)**
435 : Pops the current context off of the stack, if one exists.
437 **BclContext bcl_context(**_void_**)**
439 : Returns the current context, or **NULL** if no context exists.
441 **void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
443 : Frees all numbers in use that are associated with *ctxt*. It is undefined
444 behavior to attempt to use a number associated with *ctxt* after calling
445 this procedure unless such numbers have been created with
446 **bcl_num_create(**_void_**)** after calling this procedure.
448 **size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
450 : Returns the **scale** for given context.
452 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
454 : Sets the **scale** for the given context to the argument *scale*.
456 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
458 : Returns the **ibase** for the given context.
460 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
462 : Sets the **ibase** for the given context to the argument *ibase*. If the
463 argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
464 clamped to **2**, and any values above **36** are clamped to **36**.
466 **size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
468 : Returns the **obase** for the given context.
470 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
472 : Sets the **obase** for the given context to the argument *obase*.
478 : An **enum** of possible error codes. See the **ERRORS** section for a
479 complete listing the codes.
481 **BclError bcl_err(BclNumber** _n_**)**
483 : Checks for errors in a **BclNumber**. All functions that can return a
484 **BclNumber** can encode an error in the number, and this function will
485 return the error, if any. If there was no error, it will return
488 There must be a valid current context.
492 All procedures in this section require a valid current context.
496 : A handle to an arbitrary-precision number. The actual number type is not
497 exposed; the **BclNumber** handle is the only way clients can refer to
498 instances of arbitrary-precision numbers.
500 **BclNumber bcl_num_create(**_void_**)**
502 : Creates and returns a **BclNumber**.
504 bcl(3) will encode an error in the return value, if there was one. The error
505 can be queried with **bcl_err(BclNumber)**. Possible errors include:
507 * **BCL_ERROR_INVALID_CONTEXT**
508 * **BCL_ERROR_FATAL_ALLOC_ERR**
510 **void bcl_num_free(BclNumber** _n_**)**
512 : Frees *n*. It is undefined behavior to use *n* after calling this function.
514 **bool bcl_num_neg(BclNumber** _n_**)**
516 : Returns **true** if *n* is negative, **false** otherwise.
518 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
520 : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
523 **size_t bcl_num_scale(BclNumber** _n_**)**
525 : Returns the *scale* of *n*.
527 The *scale* of a number is the number of decimal places it has after the
528 radix (decimal point).
530 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
532 : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
533 greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
534 less than the *scale* of *n*, *n* is truncated.
536 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
539 * **BCL_ERROR_INVALID_NUM**
540 * **BCL_ERROR_INVALID_CONTEXT**
541 * **BCL_ERROR_FATAL_ALLOC_ERR**
543 **size_t bcl_num_len(BclNumber** _n_**)**
545 : Returns the number of *significant decimal digits* in *n*.
549 All procedures in this section require a valid current context.
551 All procedures in this section consume the given **BclNumber** arguments that
552 are not given to pointer arguments. See the **Consumption and Propagation**
555 **BclNumber bcl_parse(const char \*restrict** _val_**)**
557 : Parses a number string according to the current context's **ibase** and
558 returns the resulting number.
560 *val* must be non-**NULL** and a valid string. See
561 **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
564 bcl(3) will encode an error in the return value, if there was one. The error
565 can be queried with **bcl_err(BclNumber)**. Possible errors include:
567 * **BCL_ERROR_INVALID_NUM**
568 * **BCL_ERROR_INVALID_CONTEXT**
569 * **BCL_ERROR_PARSE_INVALID_STR**
570 * **BCL_ERROR_FATAL_ALLOC_ERR**
572 **char\* bcl_string(BclNumber** _n_**)**
574 : Returns a string representation of *n* according the the current context's
575 **ibase**. The string is dynamically allocated and must be freed by the
578 *n* is consumed; it cannot be used after the call. See the
579 **Consumption and Propagation** subsection below.
581 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
583 : Converts *n* into a **BclBigDig** and returns the result in the space
584 pointed to by *result*.
586 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
588 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
591 * **BCL_ERROR_INVALID_NUM**
592 * **BCL_ERROR_INVALID_CONTEXT**
593 * **BCL_ERROR_MATH_OVERFLOW**
595 *n* is consumed; it cannot be used after the call. See the
596 **Consumption and Propagation** subsection below.
598 **BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
600 : Creates a **BclNumber** from *val*.
602 bcl(3) will encode an error in the return value, if there was one. The error
603 can be queried with **bcl_err(BclNumber)**. Possible errors include:
605 * **BCL_ERROR_INVALID_CONTEXT**
606 * **BCL_ERROR_FATAL_ALLOC_ERR**
610 All procedures in this section require a valid current context.
612 All procedures in this section can return the following errors:
614 * **BCL_ERROR_INVALID_NUM**
615 * **BCL_ERROR_INVALID_CONTEXT**
616 * **BCL_ERROR_FATAL_ALLOC_ERR**
618 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
620 : Adds *a* and *b* and returns the result. The *scale* of the result is the
621 max of the *scale*s of *a* and *b*.
623 *a* and *b* are consumed; they cannot be used after the call. See the
624 **Consumption and Propagation** subsection below.
626 *a* and *b* can be the same number.
628 bcl(3) will encode an error in the return value, if there was one. The error
629 can be queried with **bcl_err(BclNumber)**. Possible errors include:
631 * **BCL_ERROR_INVALID_NUM**
632 * **BCL_ERROR_INVALID_CONTEXT**
633 * **BCL_ERROR_FATAL_ALLOC_ERR**
635 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
637 : Subtracts *b* from *a* and returns the result. The *scale* of the result is
638 the max of the *scale*s of *a* and *b*.
640 *a* and *b* are consumed; they cannot be used after the call. See the
641 **Consumption and Propagation** subsection below.
643 *a* and *b* can be the same number.
645 bcl(3) will encode an error in the return value, if there was one. The error
646 can be queried with **bcl_err(BclNumber)**. Possible errors include:
648 * **BCL_ERROR_INVALID_NUM**
649 * **BCL_ERROR_INVALID_CONTEXT**
650 * **BCL_ERROR_FATAL_ALLOC_ERR**
652 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
654 : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
655 *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
656 to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
657 **max()** return the obvious values.
659 *a* and *b* are consumed; they cannot be used after the call. See the
660 **Consumption and Propagation** subsection below.
662 *a* and *b* can be the same number.
664 bcl(3) will encode an error in the return value, if there was one. The error
665 can be queried with **bcl_err(BclNumber)**. Possible errors include:
667 * **BCL_ERROR_INVALID_NUM**
668 * **BCL_ERROR_INVALID_CONTEXT**
669 * **BCL_ERROR_FATAL_ALLOC_ERR**
671 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
673 : Divides *a* by *b* and returns the result. The *scale* of the result is the
674 *scale* of the current context.
678 *a* and *b* are consumed; they cannot be used after the call. See the
679 **Consumption and Propagation** subsection below.
681 *a* and *b* can be the same number.
683 bcl(3) will encode an error in the return value, if there was one. The error
684 can be queried with **bcl_err(BclNumber)**. Possible errors include:
686 * **BCL_ERROR_INVALID_NUM**
687 * **BCL_ERROR_INVALID_CONTEXT**
688 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
689 * **BCL_ERROR_FATAL_ALLOC_ERR**
691 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
693 : Divides *a* by *b* to the *scale* of the current context, computes the
694 modulus **a-(a/b)\*b**, and returns the modulus.
698 *a* and *b* are consumed; they cannot be used after the call. See the
699 **Consumption and Propagation** subsection below.
701 *a* and *b* can be the same number.
703 bcl(3) will encode an error in the return value, if there was one. The error
704 can be queried with **bcl_err(BclNumber)**. Possible errors include:
706 * **BCL_ERROR_INVALID_NUM**
707 * **BCL_ERROR_INVALID_CONTEXT**
708 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
709 * **BCL_ERROR_FATAL_ALLOC_ERR**
711 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
713 : Calculates *a* to the power of *b* to the *scale* of the current context.
714 *b* must be an integer, but can be negative. If it is negative, *a* must
717 *b* must be an integer. If *b* is negative, *a* must not be **0**.
719 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
721 *a* and *b* are consumed; they cannot be used after the call. See the
722 **Consumption and Propagation** subsection below.
724 *a* and *b* can be the same number.
726 bcl(3) will encode an error in the return value, if there was one. The error
727 can be queried with **bcl_err(BclNumber)**. Possible errors include:
729 * **BCL_ERROR_INVALID_NUM**
730 * **BCL_ERROR_INVALID_CONTEXT**
731 * **BCL_ERROR_MATH_NON_INTEGER**
732 * **BCL_ERROR_MATH_OVERFLOW**
733 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
734 * **BCL_ERROR_FATAL_ALLOC_ERR**
736 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
738 : Shifts *a* left (moves the radix right) by *b* places and returns the
739 result. This is done in decimal. *b* must be an integer.
741 *b* must be an integer.
743 *a* and *b* are consumed; they cannot be used after the call. See the
744 **Consumption and Propagation** subsection below.
746 *a* and *b* can be the same number.
748 bcl(3) will encode an error in the return value, if there was one. The error
749 can be queried with **bcl_err(BclNumber)**. Possible errors include:
751 * **BCL_ERROR_INVALID_NUM**
752 * **BCL_ERROR_INVALID_CONTEXT**
753 * **BCL_ERROR_MATH_NON_INTEGER**
754 * **BCL_ERROR_FATAL_ALLOC_ERR**
756 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
758 : Shifts *a* right (moves the radix left) by *b* places and returns the
759 result. This is done in decimal. *b* must be an integer.
761 *b* must be an integer.
763 *a* and *b* are consumed; they cannot be used after the call. See the
764 **Consumption and Propagation** subsection below.
766 *a* and *b* can be the same number.
768 bcl(3) will encode an error in the return value, if there was one. The error
769 can be queried with **bcl_err(BclNumber)**. Possible errors include:
771 * **BCL_ERROR_INVALID_NUM**
772 * **BCL_ERROR_INVALID_CONTEXT**
773 * **BCL_ERROR_MATH_NON_INTEGER**
774 * **BCL_ERROR_FATAL_ALLOC_ERR**
776 **BclNumber bcl_sqrt(BclNumber** _a_**)**
778 : Calculates the square root of *a* and returns the result. The *scale* of the
779 result is equal to the **scale** of the current context.
781 *a* cannot be negative.
783 *a* is consumed; it cannot be used after the call. See the
784 **Consumption and Propagation** subsection below.
786 bcl(3) will encode an error in the return value, if there was one. The error
787 can be queried with **bcl_err(BclNumber)**. Possible errors include:
789 * **BCL_ERROR_INVALID_NUM**
790 * **BCL_ERROR_INVALID_CONTEXT**
791 * **BCL_ERROR_MATH_NEGATIVE**
792 * **BCL_ERROR_FATAL_ALLOC_ERR**
794 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
796 : Divides *a* by *b* and returns the quotient in a new number which is put
797 into the space pointed to by *c*, and puts the modulus in a new number which
798 is put into the space pointed to by *d*.
802 *a* and *b* are consumed; they cannot be used after the call. See the
803 **Consumption and Propagation** subsection below.
805 *c* and *d* cannot point to the same place, nor can they point to the space
806 occupied by *a* or *b*.
808 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
811 * **BCL_ERROR_INVALID_NUM**
812 * **BCL_ERROR_INVALID_CONTEXT**
813 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
814 * **BCL_ERROR_FATAL_ALLOC_ERR**
816 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
818 : Computes a modular exponentiation where *a* is the base, *b* is the
819 exponent, and *c* is the modulus, and returns the result. The *scale* of the
820 result is equal to the **scale** of the current context.
822 *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
825 *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
826 **Consumption and Propagation** subsection below.
828 bcl(3) will encode an error in the return value, if there was one. The error
829 can be queried with **bcl_err(BclNumber)**. Possible errors include:
831 * **BCL_ERROR_INVALID_NUM**
832 * **BCL_ERROR_INVALID_CONTEXT**
833 * **BCL_ERROR_MATH_NEGATIVE**
834 * **BCL_ERROR_MATH_NON_INTEGER**
835 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
836 * **BCL_ERROR_FATAL_ALLOC_ERR**
840 **void bcl_zero(BclNumber** _n_**)**
844 **void bcl_one(BclNumber** _n_**)**
848 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
850 : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
851 *a* is less than *b*, and **>0** if *a* is greater than *b*.
853 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
855 : Copies *s* into *d*.
857 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
860 * **BCL_ERROR_INVALID_NUM**
861 * **BCL_ERROR_INVALID_CONTEXT**
862 * **BCL_ERROR_FATAL_ALLOC_ERR**
864 **BclNumber bcl_dup(BclNumber** _s_**)**
866 : Creates and returns a new **BclNumber** that is a copy of *s*.
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_NUM**
872 * **BCL_ERROR_INVALID_CONTEXT**
873 * **BCL_ERROR_FATAL_ALLOC_ERR**
875 ## Pseudo-Random Number Generator
877 The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
878 seed twice, it will produce the same sequence of pseudo-random numbers twice.
880 By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
881 that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
882 then calling **rand()** for each byte, since **rand()** is only guaranteed to
885 This should provide fairly good seeding in the standard case while also
886 remaining fairly portable.
888 If necessary, the PRNG can be reseeded with one of the following functions:
890 * **bcl_rand_seedWithNum(BclNumber)**
891 * **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
892 * **bcl_rand_reseed(**_void_**)**
894 The following items allow clients to use the pseudo-random number generator. All
895 procedures require a valid current context.
899 : The number of **unsigned long**'s in a seed for bcl(3)'s random number
904 : The size, in **char**'s, of a seed for bcl(3)'s random number generator.
908 : bcl(3)'s overflow type (see the **PERFORMANCE** section).
912 : An unsigned integer type returned by bcl(3)'s random number generator.
914 **BclNumber bcl_irand(BclNumber** _a_**)**
916 : Returns a random number that is not larger than *a* in a new number. If *a*
917 is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
918 so it is not bound to the size of **BclRandInt**. This is done by generating
919 as many random numbers as necessary, multiplying them by certain exponents,
920 and adding them all together.
922 *a* must be an integer and non-negative.
924 *a* is consumed; it cannot be used after the call. See the
925 **Consumption and Propagation** subsection below.
927 This procedure requires a valid current context.
929 bcl(3) will encode an error in the return value, if there was one. The error
930 can be queried with **bcl_err(BclNumber)**. Possible errors include:
932 * **BCL_ERROR_INVALID_NUM**
933 * **BCL_ERROR_INVALID_CONTEXT**
934 * **BCL_ERROR_MATH_NEGATIVE**
935 * **BCL_ERROR_MATH_NON_INTEGER**
936 * **BCL_ERROR_FATAL_ALLOC_ERR**
938 **BclNumber bcl_frand(size_t** _places_**)**
940 : Returns a random number between **0** (inclusive) and **1** (exclusive) that
941 has *places* decimal digits after the radix (decimal point). There are no
944 This procedure requires a valid current context.
946 bcl(3) will encode an error in the return value, if there was one. The error
947 can be queried with **bcl_err(BclNumber)**. Possible errors include:
949 * **BCL_ERROR_INVALID_CONTEXT**
950 * **BCL_ERROR_FATAL_ALLOC_ERR**
952 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
954 : Returns a random number less than *a* with *places* decimal digits after the
955 radix (decimal point). There are no limits on *a* or *places*.
957 *a* must be an integer and non-negative.
959 *a* is consumed; it cannot be used after the call. See the
960 **Consumption and Propagation** subsection below.
962 This procedure requires a valid current context.
964 bcl(3) will encode an error in the return value, if there was one. The error
965 can be queried with **bcl_err(BclNumber)**. Possible errors include:
967 * **BCL_ERROR_INVALID_NUM**
968 * **BCL_ERROR_INVALID_CONTEXT**
969 * **BCL_ERROR_MATH_NEGATIVE**
970 * **BCL_ERROR_MATH_NON_INTEGER**
971 * **BCL_ERROR_FATAL_ALLOC_ERR**
973 **BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
975 : Seeds the PRNG with *n*.
977 *n* is *not* consumed.
979 This procedure requires a valid current context.
981 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
984 * **BCL_ERROR_INVALID_NUM**
985 * **BCL_ERROR_INVALID_CONTEXT**
987 Note that if **bcl_rand_seed2num(**_void_**)** or
988 **bcl_rand_seed2num_err(BclNumber)** are called right after this function,
989 they are not guaranteed to return a number equal to *n*.
991 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
993 : Seeds the PRNG with the bytes in *seed*.
995 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
998 * **BCL_ERROR_INVALID_CONTEXT**
1000 **void bcl_rand_reseed(**_void_**)**
1002 : Reseeds the PRNG with the default reseeding behavior. First, it attempts to
1003 read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
1005 This procedure cannot fail.
1007 **BclNumber bcl_rand_seed2num(**_void_**)**
1009 : Returns the current seed of the PRNG as a **BclNumber**.
1011 This procedure requires a valid current context.
1013 bcl(3) will encode an error in the return value, if there was one. The error
1014 can be queried with **bcl_err(BclNumber)**. Possible errors include:
1016 * **BCL_ERROR_INVALID_CONTEXT**
1017 * **BCL_ERROR_FATAL_ALLOC_ERR**
1019 **BclRandInt bcl_rand_int(**_void_**)**
1021 : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
1023 This procedure cannot fail.
1025 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
1027 : Returns a random integer between **0** and *bound* (exclusive). Bias is
1028 removed before returning the integer.
1030 This procedure cannot fail.
1032 ## Consumption and Propagation
1034 Some functions are listed as consuming some or all of their arguments. This
1035 means that the arguments are freed, regardless of if there were errors or not.
1037 This is to enable compact code like the following:
1039 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
1041 If arguments to those functions were not consumed, memory would be leaked until
1042 reclaimed with **bcl_ctxt_freeNums(BclContext)**.
1044 When errors occur, they are propagated through. The result should always be
1045 checked with **bcl_err(BclNumber)**, so the example above should properly
1048 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
1049 if (bc_num_err(n) != BCL_ERROR_NONE) {
1050 // Handle the error.
1055 Most functions in bcl(3) return, directly or indirectly, any one of the error
1056 codes defined in **BclError**. The complete list of codes is the following:
1060 : Success; no error occurred.
1062 **BCL_ERROR_INVALID_NUM**
1064 : An invalid **BclNumber** was given as a parameter.
1066 **BCL_ERROR_INVALID_CONTEXT**
1068 : An invalid **BclContext** is being used.
1070 **BCL_ERROR_MATH_NEGATIVE**
1072 : A negative number was given as an argument to a parameter that cannot accept
1073 negative numbers, such as for square roots.
1075 **BCL_ERROR_MATH_NON_INTEGER**
1077 : A non-integer was given as an argument to a parameter that cannot accept
1078 non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
1080 **BCL_ERROR_MATH_OVERFLOW**
1082 : A number that would overflow its result was given as an argument, such as
1083 for converting a **BclNumber** to a **BclBigDig**.
1085 **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1087 : A divide by zero occurred.
1089 **BCL_ERROR_PARSE_INVALID_STR**
1091 : An invalid number string was passed to a parsing function.
1093 A valid number string can only be one radix (period). In addition, any
1094 lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
1095 allowed for the first character to be a dash. In that case, the number is
1096 considered to be negative.
1098 There is one exception to the above: one lowercase **e** is allowed in the
1099 number, after the radix, if it exists. If the letter **e** exists, the
1100 number is considered to be in scientific notation, where the part before the
1101 **e** is the number, and the part after, which must be an integer, is the
1102 exponent. There can be a dash right after the **e** to indicate a negative
1105 **WARNING**: Both the number and the exponent in scientific notation are
1106 interpreted according to the current **ibase**, but the number is still
1107 multiplied by **10\^exponent** regardless of the current **ibase**. For
1108 example, if **ibase** is **16** and bcl(3) is given the number string
1109 **FFeA**, the resulting decimal number will be **2550000000000**, and if
1110 bcl(3) is given the number string **10e-4**, the resulting decimal number
1113 **BCL_ERROR_FATAL_ALLOC_ERR**
1115 : bcl(3) failed to allocate memory.
1117 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1118 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1119 be turned off later by calling that same function with a **false** argument.
1120 By default, this behavior is off.
1122 It is highly recommended that client libraries do *not* activate this
1125 **BCL_ERROR_FATAL_UNKNOWN_ERR**
1127 : An unknown error occurred.
1129 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1130 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1131 be turned off later by calling that same function with a **false** argument.
1132 By default, this behavior is off.
1134 It is highly recommended that client libraries do *not* activate this
1139 bcl(3) is *MT-Safe*: it is safe to call any functions from more than one thread.
1140 However, is is *not* safe to pass any data between threads except for strings
1141 returned by **bcl_string()**.
1143 bcl(3) is not *async-signal-safe*. It was not possible to make bcl(3) safe with
1144 signals and also make it safe with multiple threads. If it is necessary to be
1145 able to interrupt bcl(3), spawn a separate thread to run the calculation.
1149 Most bc(1) implementations use **char** types to calculate the value of **1**
1150 decimal digit at a time, but that can be slow. bcl(3) does something
1153 It uses large integers to calculate more than **1** decimal digit at a time. If
1154 built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1155 **64**, then each integer has **9** decimal digits. If built in an environment
1156 where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1157 value (the number of decimal digits per large integer) is called
1160 In addition, this bcl(3) uses an even larger integer for overflow checking. This
1161 integer type depends on the value of **BC_LONG_BIT**, but is always at least
1162 twice as large as the integer type used to store digits.
1166 The following are the limits on bcl(3):
1170 : The number of bits in the **long** type in the environment where bcl(3) was
1171 built. This determines how many decimal digits can be stored in a single
1172 large integer (see the **PERFORMANCE** section).
1176 : The number of decimal digits per large integer (see the **PERFORMANCE**
1177 section). Depends on **BC_LONG_BIT**.
1181 : The max decimal number that each large integer can store (see
1182 **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1186 : The max number that the overflow type (see the **PERFORMANCE** section) can
1187 hold. Depends on **BC_LONG_BIT**.
1191 : The maximum output base. Set at **BC_BASE_POW**.
1195 : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1199 : The maximum length of a number (in decimal digits), which includes digits
1200 after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1204 : The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1205 Set at **2\^BC_LONG_BIT-1**.
1209 : The maximum allowable exponent (positive or negative). Set at
1210 **BC_OVERFLOW_MAX**.
1212 These limits are meant to be effectively non-existent; the limits are so large
1213 (at least on 64-bit machines) that there should not be any point at which they
1214 become a problem. In fact, memory should be exhausted before these limits should
1223 bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017
1224 (“POSIX.1-2017”) specification at
1225 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html for bc(1).
1227 Note that the specification explicitly says that bc(1) only accepts numbers that
1228 use a period (**.**) as a radix point, regardless of the value of
1229 **LC_NUMERIC**. This is also true of bcl(3).
1233 None are known. Report bugs at https://git.gavinhoward.com/gavin/bc.
1237 Gavin D. Howard <gavin@gavinhoward.com> and contributors.