3 SPDX-License-Identifier: BSD-2-Clause
5 Copyright (c) 2018-2021 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 **bool bcl_leadingZeroes(**_void_**);**
66 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**);**
68 **void bcl_gc(**_void_**);**
72 These items will allow clients to handle contexts, which are isolated from each
73 other. This allows more than one client to use bcl(3) in the same program.
77 **typedef struct BclCtxt\* BclContext;**
79 **BclContext bcl_ctxt_create(**_void_**);**
81 **void bcl_ctxt_free(BclContext** _ctxt_**);**
83 **BclError bcl_pushContext(BclContext** _ctxt_**);**
85 **void bcl_popContext(**_void_**);**
87 **BclContext bcl_context(**_void_**);**
89 **void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
91 **size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
93 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
95 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
97 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
99 **size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
101 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
105 These items allow clients to handle errors.
107 **typedef enum BclError BclError;**
109 **BclError bcl_err(BclNumber** _n_**);**
113 These items allow clients to manipulate and query the arbitrary-precision
114 numbers managed by bcl(3).
116 **typedef struct { size_t i; } BclNumber;**
118 **BclNumber bcl_num_create(**_void_**);**
120 **void bcl_num_free(BclNumber** _n_**);**
122 **bool bcl_num_neg(BclNumber** _n_**);**
124 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
126 **size_t bcl_num_scale(BclNumber** _n_**);**
128 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
130 **size_t bcl_num_len(BclNumber** _n_**);**
134 These items allow clients to convert numbers into and from strings and integers.
136 **BclNumber bcl_parse(const char \*restrict** _val_**);**
138 **char\* bcl_string(BclNumber** _n_**);**
140 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
142 **BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
146 These items allow clients to run math on numbers.
148 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
150 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
152 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
154 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
156 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
158 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
160 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
162 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
164 **BclNumber bcl_sqrt(BclNumber** _a_**);**
166 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
168 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
172 These items are miscellaneous.
174 **void bcl_zero(BclNumber** _n_**);**
176 **void bcl_one(BclNumber** _n_**);**
178 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
180 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
182 **BclNumber bcl_dup(BclNumber** _s_**);**
184 ## Pseudo-Random Number Generator
186 These items allow clients to manipulate the seeded pseudo-random number
189 **#define BCL_SEED_ULONGS**
191 **#define BCL_SEED_SIZE**
193 **typedef unsigned long BclBigDig;**
195 **typedef unsigned long BclRandInt;**
197 **BclNumber bcl_irand(BclNumber** _a_**);**
199 **BclNumber bcl_frand(size_t** _places_**);**
201 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
203 **BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
205 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
207 **void bcl_rand_reseed(**_void_**);**
209 **BclNumber bcl_rand_seed2num(**_void_**);**
211 **BclRandInt bcl_rand_int(**_void_**);**
213 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
217 bcl(3) is a library that implements arbitrary-precision decimal math, as
218 [standardized by POSIX][1] in bc(1).
220 bcl(3) is async-signal-safe if **bcl_handleSignal(**_void_**)** is used
221 properly. (See the **SIGNAL HANDLING** section.)
223 bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and
224 **Bc** prefixes for symbol names without collision.
226 All of the items in its interface are described below. See the documentation for
227 each function for what each function can return.
231 **void bcl_handleSignal(**_void_**)**
233 : An async-signal-safe function that can be called from a signal handler. If
234 called from a signal handler on the same thread as any executing bcl(3)
235 functions, it will interrupt the functions and force them to return early.
236 It is undefined behavior if this function is called from a thread that is
237 *not* executing any bcl(3) functions while any bcl(3) functions are
240 If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
241 return to its caller.
243 See the **SIGNAL HANDLING** section.
245 **bool bcl_running(**_void_**)**
247 : An async-signal-safe function that can be called from a signal handler. It
248 will return **true** if any bcl(3) procedures are running, which means it is
249 safe to call **bcl_handleSignal(**_void_**)**. Otherwise, it returns
252 See the **SIGNAL HANDLING** section.
256 **BclError bcl_init(**_void_**)**
258 : Initializes this library. This function can be called multiple times, but
259 each call must be matched by a call to **bcl_free(**_void_**)**. This is to
260 make it possible for multiple libraries and applications to initialize
261 bcl(3) without problem.
263 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
266 * **BCL_ERROR_FATAL_ALLOC_ERR**
268 This function must be the first one clients call. Calling any other
269 function without calling this one first is undefined behavior.
271 **void bcl_free(**_void_**)**
273 : Decrements bcl(3)'s reference count and frees the data associated with it if
274 the reference count is **0**.
276 This function must be the last one clients call. Calling this function
277 before calling any other function is undefined behavior.
279 **bool bcl_abortOnFatalError(**_void_**)**
281 : Queries and returns the current state of calling **abort()** on fatal
282 errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
285 If activated, clients do not need to check for fatal errors.
287 The default is **false**.
289 **void bcl_setAbortOnFatalError(bool** _abrt_**)**
291 : Sets the state of calling **abort()** on fatal errors. If *abrt* is
292 **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
293 call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
296 If activated, clients do not need to check for fatal errors.
298 **bool bcl_leadingZeroes(**_void_**)**
300 : Queries and returns the state of whether leading zeroes are added to strings
301 returned by **bcl_string()** when numbers are greater than **-1**, less than
302 **1**, and not equal to **0**. If **true** is returned, then leading zeroes
305 The default is **false**.
307 **void bcl_setLeadingZeroes(bool** _leadingZeroes_**)**
309 : Sets the state of whether leading zeroes are added to strings returned by
310 **bcl_string()** when numbers are greater than **-1**, less than **1**, and
311 not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be
312 added to strings returned by **bcl_string()**.
314 **void bcl_gc(**_void_**)**
316 : Garbage collects cached instances of arbitrary-precision numbers. This only
317 frees the memory of numbers that are *not* in use, so it is safe to call at
322 All procedures that take a **BclContext** parameter a require a valid context as
327 : A forward declaration for a hidden **struct** type. Clients cannot access
328 the internals of the **struct** type directly. All interactions with the
329 type are done through pointers. See **BclContext** below.
333 : A typedef to a pointer of **struct BclCtxt**. This is the only handle
334 clients can get to **struct BclCtxt**.
336 A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
337 well as a list of numbers.
339 **scale** is a value used to control how many decimal places calculations
340 should use. A value of **0** means that calculations are done on integers
341 only, where applicable, and a value of 20, for example, means that all
342 applicable calculations return results with 20 decimal places. The default
345 **ibase** is a value used to control the input base. The minimum **ibase**
346 is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
347 parsed as though they are in binary, and any digits larger than **1** are
348 clamped. Likewise, a value of **10** means that numbers are parsed as though
349 they are decimal, and any larger digits are clamped. The default is **10**.
351 **obase** is a value used to control the output base. The minimum **obase**
352 is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
354 Numbers created in one context are not valid in another context. It is
355 undefined behavior to use a number created in a different context. Contexts
356 are meant to isolate the numbers used by different clients in the same
359 **BclContext bcl_ctxt_create(**_void_**)**
361 : Creates a context and returns it. Returns **NULL** if there was an error.
363 **void bcl_ctxt_free(BclContext** _ctxt_**)**
365 : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
366 attempt to use an invalid context.
368 **BclError bcl_pushContext(BclContext** _ctxt_**)**
370 : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
371 with **bcl_ctxt_create(**_void_**)**.
373 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
376 * **BCL_ERROR_FATAL_ALLOC_ERR**
378 There *must* be a valid context to do any arithmetic.
380 **void bcl_popContext(**_void_**)**
382 : Pops the current context off of the stack, if one exists.
384 **BclContext bcl_context(**_void_**)**
386 : Returns the current context, or **NULL** if no context exists.
388 **void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
390 : Frees all numbers in use that are associated with *ctxt*. It is undefined
391 behavior to attempt to use a number associated with *ctxt* after calling
392 this procedure unless such numbers have been created with
393 **bcl_num_create(**_void_**)** after calling this procedure.
395 **size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
397 : Returns the **scale** for given context.
399 **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
401 : Sets the **scale** for the given context to the argument *scale*.
403 **size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
405 : Returns the **ibase** for the given context.
407 **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
409 : Sets the **ibase** for the given context to the argument *ibase*. If the
410 argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
411 clamped to **2**, and any values above **36** are clamped to **36**.
413 **size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
415 : Returns the **obase** for the given context.
417 **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
419 : Sets the **obase** for the given context to the argument *obase*.
425 : An **enum** of possible error codes. See the **ERRORS** section for a
426 complete listing the codes.
428 **BclError bcl_err(BclNumber** _n_**)**
430 : Checks for errors in a **BclNumber**. All functions that can return a
431 **BclNumber** can encode an error in the number, and this function will
432 return the error, if any. If there was no error, it will return
435 There must be a valid current context.
439 All procedures in this section require a valid current context.
443 : A handle to an arbitrary-precision number. The actual number type is not
444 exposed; the **BclNumber** handle is the only way clients can refer to
445 instances of arbitrary-precision numbers.
447 **BclNumber bcl_num_create(**_void_**)**
449 : Creates and returns a **BclNumber**.
451 bcl(3) will encode an error in the return value, if there was one. The error
452 can be queried with **bcl_err(BclNumber)**. Possible errors include:
454 * **BCL_ERROR_INVALID_CONTEXT**
455 * **BCL_ERROR_FATAL_ALLOC_ERR**
457 **void bcl_num_free(BclNumber** _n_**)**
459 : Frees *n*. It is undefined behavior to use *n* after calling this function.
461 **bool bcl_num_neg(BclNumber** _n_**)**
463 : Returns **true** if *n* is negative, **false** otherwise.
465 **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
467 : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
470 **size_t bcl_num_scale(BclNumber** _n_**)**
472 : Returns the *scale* of *n*.
474 The *scale* of a number is the number of decimal places it has after the
475 radix (decimal point).
477 **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
479 : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
480 greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
481 less than the *scale* of *n*, *n* is truncated.
483 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
486 * **BCL_ERROR_INVALID_NUM**
487 * **BCL_ERROR_INVALID_CONTEXT**
488 * **BCL_ERROR_FATAL_ALLOC_ERR**
490 **size_t bcl_num_len(BclNumber** _n_**)**
492 : Returns the number of *significant decimal digits* in *n*.
496 All procedures in this section require a valid current context.
498 All procedures in this section consume the given **BclNumber** arguments that
499 are not given to pointer arguments. See the **Consumption and Propagation**
502 **BclNumber bcl_parse(const char \*restrict** _val_**)**
504 : Parses a number string according to the current context's **ibase** and
505 returns the resulting number.
507 *val* must be non-**NULL** and a valid string. See
508 **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
511 bcl(3) will encode an error in the return value, if there was one. The error
512 can be queried with **bcl_err(BclNumber)**. Possible errors include:
514 * **BCL_ERROR_INVALID_NUM**
515 * **BCL_ERROR_INVALID_CONTEXT**
516 * **BCL_ERROR_PARSE_INVALID_STR**
517 * **BCL_ERROR_FATAL_ALLOC_ERR**
519 **char\* bcl_string(BclNumber** _n_**)**
521 : Returns a string representation of *n* according the the current context's
522 **ibase**. The string is dynamically allocated and must be freed by the
525 *n* is consumed; it cannot be used after the call. See the
526 **Consumption and Propagation** subsection below.
528 **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
530 : Converts *n* into a **BclBigDig** and returns the result in the space
531 pointed to by *result*.
533 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
535 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
538 * **BCL_ERROR_INVALID_NUM**
539 * **BCL_ERROR_INVALID_CONTEXT**
540 * **BCL_ERROR_MATH_OVERFLOW**
542 *n* is consumed; it cannot be used after the call. See the
543 **Consumption and Propagation** subsection below.
545 **BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
547 : Creates a **BclNumber** from *val*.
549 bcl(3) will encode an error in the return value, if there was one. The error
550 can be queried with **bcl_err(BclNumber)**. Possible errors include:
552 * **BCL_ERROR_INVALID_CONTEXT**
553 * **BCL_ERROR_FATAL_ALLOC_ERR**
557 All procedures in this section require a valid current context.
559 All procedures in this section can return the following errors:
561 * **BCL_ERROR_INVALID_NUM**
562 * **BCL_ERROR_INVALID_CONTEXT**
563 * **BCL_ERROR_FATAL_ALLOC_ERR**
565 **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
567 : Adds *a* and *b* and returns the result. The *scale* of the result is the
568 max of the *scale*s of *a* and *b*.
570 *a* and *b* are consumed; they cannot be used after the call. See the
571 **Consumption and Propagation** subsection below.
573 *a* and *b* can be the same number.
575 bcl(3) will encode an error in the return value, if there was one. The error
576 can be queried with **bcl_err(BclNumber)**. Possible errors include:
578 * **BCL_ERROR_INVALID_NUM**
579 * **BCL_ERROR_INVALID_CONTEXT**
580 * **BCL_ERROR_FATAL_ALLOC_ERR**
582 **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
584 : Subtracts *b* from *a* and returns the result. The *scale* of the result is
585 the max of the *scale*s of *a* and *b*.
587 *a* and *b* are consumed; they cannot be used after the call. See the
588 **Consumption and Propagation** subsection below.
590 *a* and *b* can be the same number.
592 bcl(3) will encode an error in the return value, if there was one. The error
593 can be queried with **bcl_err(BclNumber)**. Possible errors include:
595 * **BCL_ERROR_INVALID_NUM**
596 * **BCL_ERROR_INVALID_CONTEXT**
597 * **BCL_ERROR_FATAL_ALLOC_ERR**
599 **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
601 : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
602 *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
603 to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
604 **max()** return the obvious values.
606 *a* and *b* are consumed; they cannot be used after the call. See the
607 **Consumption and Propagation** subsection below.
609 *a* and *b* can be the same number.
611 bcl(3) will encode an error in the return value, if there was one. The error
612 can be queried with **bcl_err(BclNumber)**. Possible errors include:
614 * **BCL_ERROR_INVALID_NUM**
615 * **BCL_ERROR_INVALID_CONTEXT**
616 * **BCL_ERROR_FATAL_ALLOC_ERR**
618 **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
620 : Divides *a* by *b* and returns the result. The *scale* of the result is the
621 *scale* of the current context.
625 *a* and *b* are consumed; they cannot be used after the call. See the
626 **Consumption and Propagation** subsection below.
628 *a* and *b* can be the same number.
630 bcl(3) will encode an error in the return value, if there was one. The error
631 can be queried with **bcl_err(BclNumber)**. Possible errors include:
633 * **BCL_ERROR_INVALID_NUM**
634 * **BCL_ERROR_INVALID_CONTEXT**
635 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
636 * **BCL_ERROR_FATAL_ALLOC_ERR**
638 **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
640 : Divides *a* by *b* to the *scale* of the current context, computes the
641 modulus **a-(a/b)\*b**, and returns the modulus.
645 *a* and *b* are consumed; they cannot be used after the call. See the
646 **Consumption and Propagation** subsection below.
648 *a* and *b* can be the same number.
650 bcl(3) will encode an error in the return value, if there was one. The error
651 can be queried with **bcl_err(BclNumber)**. Possible errors include:
653 * **BCL_ERROR_INVALID_NUM**
654 * **BCL_ERROR_INVALID_CONTEXT**
655 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
656 * **BCL_ERROR_FATAL_ALLOC_ERR**
658 **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
660 : Calculates *a* to the power of *b* to the *scale* of the current context.
661 *b* must be an integer, but can be negative. If it is negative, *a* must
664 *b* must be an integer. If *b* is negative, *a* must not be **0**.
666 *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
668 *a* and *b* are consumed; they cannot be used after the call. See the
669 **Consumption and Propagation** subsection below.
671 *a* and *b* can be the same number.
673 bcl(3) will encode an error in the return value, if there was one. The error
674 can be queried with **bcl_err(BclNumber)**. Possible errors include:
676 * **BCL_ERROR_INVALID_NUM**
677 * **BCL_ERROR_INVALID_CONTEXT**
678 * **BCL_ERROR_MATH_NON_INTEGER**
679 * **BCL_ERROR_MATH_OVERFLOW**
680 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
681 * **BCL_ERROR_FATAL_ALLOC_ERR**
683 **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
685 : Shifts *a* left (moves the radix right) by *b* places and returns the
686 result. This is done in decimal. *b* must be an integer.
688 *b* must be an integer.
690 *a* and *b* are consumed; they cannot be used after the call. See the
691 **Consumption and Propagation** subsection below.
693 *a* and *b* can be the same number.
695 bcl(3) will encode an error in the return value, if there was one. The error
696 can be queried with **bcl_err(BclNumber)**. Possible errors include:
698 * **BCL_ERROR_INVALID_NUM**
699 * **BCL_ERROR_INVALID_CONTEXT**
700 * **BCL_ERROR_MATH_NON_INTEGER**
701 * **BCL_ERROR_FATAL_ALLOC_ERR**
703 **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
705 : Shifts *a* right (moves the radix left) by *b* places and returns the
706 result. This is done in decimal. *b* must be an integer.
708 *b* must be an integer.
710 *a* and *b* are consumed; they cannot be used after the call. See the
711 **Consumption and Propagation** subsection below.
713 *a* and *b* can be the same number.
715 bcl(3) will encode an error in the return value, if there was one. The error
716 can be queried with **bcl_err(BclNumber)**. Possible errors include:
718 * **BCL_ERROR_INVALID_NUM**
719 * **BCL_ERROR_INVALID_CONTEXT**
720 * **BCL_ERROR_MATH_NON_INTEGER**
721 * **BCL_ERROR_FATAL_ALLOC_ERR**
723 **BclNumber bcl_sqrt(BclNumber** _a_**)**
725 : Calculates the square root of *a* and returns the result. The *scale* of the
726 result is equal to the **scale** of the current context.
728 *a* cannot be negative.
730 *a* is consumed; it cannot be used after the call. See the
731 **Consumption and Propagation** subsection below.
733 bcl(3) will encode an error in the return value, if there was one. The error
734 can be queried with **bcl_err(BclNumber)**. Possible errors include:
736 * **BCL_ERROR_INVALID_NUM**
737 * **BCL_ERROR_INVALID_CONTEXT**
738 * **BCL_ERROR_MATH_NEGATIVE**
739 * **BCL_ERROR_FATAL_ALLOC_ERR**
741 **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
743 : Divides *a* by *b* and returns the quotient in a new number which is put
744 into the space pointed to by *c*, and puts the modulus in a new number which
745 is put into the space pointed to by *d*.
749 *a* and *b* are consumed; they cannot be used after the call. See the
750 **Consumption and Propagation** subsection below.
752 *c* and *d* cannot point to the same place, nor can they point to the space
753 occupied by *a* or *b*.
755 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
758 * **BCL_ERROR_INVALID_NUM**
759 * **BCL_ERROR_INVALID_CONTEXT**
760 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
761 * **BCL_ERROR_FATAL_ALLOC_ERR**
763 **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
765 : Computes a modular exponentiation where *a* is the base, *b* is the
766 exponent, and *c* is the modulus, and returns the result. The *scale* of the
767 result is equal to the **scale** of the current context.
769 *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
772 *a*, *b*, and *c* are consumed; they cannot be used after the call. See the
773 **Consumption and Propagation** subsection below.
775 bcl(3) will encode an error in the return value, if there was one. The error
776 can be queried with **bcl_err(BclNumber)**. Possible errors include:
778 * **BCL_ERROR_INVALID_NUM**
779 * **BCL_ERROR_INVALID_CONTEXT**
780 * **BCL_ERROR_MATH_NEGATIVE**
781 * **BCL_ERROR_MATH_NON_INTEGER**
782 * **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
783 * **BCL_ERROR_FATAL_ALLOC_ERR**
787 **void bcl_zero(BclNumber** _n_**)**
791 **void bcl_one(BclNumber** _n_**)**
795 **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
797 : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
798 *a* is less than *b*, and **>0** if *a* is greater than *b*.
800 **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
802 : Copies *s* into *d*.
804 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
807 * **BCL_ERROR_INVALID_NUM**
808 * **BCL_ERROR_INVALID_CONTEXT**
809 * **BCL_ERROR_FATAL_ALLOC_ERR**
811 **BclNumber bcl_dup(BclNumber** _s_**)**
813 : Creates and returns a new **BclNumber** that is a copy of *s*.
815 bcl(3) will encode an error in the return value, if there was one. The error
816 can be queried with **bcl_err(BclNumber)**. Possible errors include:
818 * **BCL_ERROR_INVALID_NUM**
819 * **BCL_ERROR_INVALID_CONTEXT**
820 * **BCL_ERROR_FATAL_ALLOC_ERR**
822 ## Pseudo-Random Number Generator
824 The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
825 seed twice, it will produce the same sequence of pseudo-random numbers twice.
827 By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
828 that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
829 then calling **rand()** for each byte, since **rand()** is only guaranteed to
832 This should provide fairly good seeding in the standard case while also
833 remaining fairly portable.
835 If necessary, the PRNG can be reseeded with one of the following functions:
837 * **bcl_rand_seedWithNum(BclNumber)**
838 * **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
839 * **bcl_rand_reseed(**_void_**)**
841 The following items allow clients to use the pseudo-random number generator. All
842 procedures require a valid current context.
846 : The number of **unsigned long**'s in a seed for bcl(3)'s random number
851 : The size, in **char**'s, of a seed for bcl(3)'s random number generator.
855 : bcl(3)'s overflow type (see the **PERFORMANCE** section).
859 : An unsigned integer type returned by bcl(3)'s random number generator.
861 **BclNumber bcl_irand(BclNumber** _a_**)**
863 : Returns a random number that is not larger than *a* in a new number. If *a*
864 is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
865 so it is not bound to the size of **BclRandInt**. This is done by generating
866 as many random numbers as necessary, multiplying them by certain exponents,
867 and adding them all together.
869 *a* must be an integer and non-negative.
871 *a* is consumed; it cannot be used after the call. See the
872 **Consumption and Propagation** subsection below.
874 This procedure requires a valid current context.
876 bcl(3) will encode an error in the return value, if there was one. The error
877 can be queried with **bcl_err(BclNumber)**. Possible errors include:
879 * **BCL_ERROR_INVALID_NUM**
880 * **BCL_ERROR_INVALID_CONTEXT**
881 * **BCL_ERROR_MATH_NEGATIVE**
882 * **BCL_ERROR_MATH_NON_INTEGER**
883 * **BCL_ERROR_FATAL_ALLOC_ERR**
885 **BclNumber bcl_frand(size_t** _places_**)**
887 : Returns a random number between **0** (inclusive) and **1** (exclusive) that
888 has *places* decimal digits after the radix (decimal point). There are no
891 This procedure requires a valid current context.
893 bcl(3) will encode an error in the return value, if there was one. The error
894 can be queried with **bcl_err(BclNumber)**. Possible errors include:
896 * **BCL_ERROR_INVALID_CONTEXT**
897 * **BCL_ERROR_FATAL_ALLOC_ERR**
899 **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
901 : Returns a random number less than *a* with *places* decimal digits after the
902 radix (decimal point). There are no limits on *a* or *places*.
904 *a* must be an integer and non-negative.
906 *a* is consumed; it cannot be used after the call. See the
907 **Consumption and Propagation** subsection below.
909 This procedure requires a valid current context.
911 bcl(3) will encode an error in the return value, if there was one. The error
912 can be queried with **bcl_err(BclNumber)**. Possible errors include:
914 * **BCL_ERROR_INVALID_NUM**
915 * **BCL_ERROR_INVALID_CONTEXT**
916 * **BCL_ERROR_MATH_NEGATIVE**
917 * **BCL_ERROR_MATH_NON_INTEGER**
918 * **BCL_ERROR_FATAL_ALLOC_ERR**
920 **BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
922 : Seeds the PRNG with *n*.
924 *n* is *not* consumed.
926 This procedure requires a valid current context.
928 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
931 * **BCL_ERROR_INVALID_NUM**
932 * **BCL_ERROR_INVALID_CONTEXT**
934 Note that if **bcl_rand_seed2num(**_void_**)** or
935 **bcl_rand_seed2num_err(BclNumber)** are called right after this function,
936 they are not guaranteed to return a number equal to *n*.
938 **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
940 : Seeds the PRNG with the bytes in *seed*.
942 If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
945 * **BCL_ERROR_INVALID_CONTEXT**
947 **void bcl_rand_reseed(**_void_**)**
949 : Reseeds the PRNG with the default reseeding behavior. First, it attempts to
950 read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
952 This procedure cannot fail.
954 **BclNumber bcl_rand_seed2num(**_void_**)**
956 : Returns the current seed of the PRNG as a **BclNumber**.
958 This procedure requires a valid current context.
960 bcl(3) will encode an error in the return value, if there was one. The error
961 can be queried with **bcl_err(BclNumber)**. Possible errors include:
963 * **BCL_ERROR_INVALID_CONTEXT**
964 * **BCL_ERROR_FATAL_ALLOC_ERR**
966 **BclRandInt bcl_rand_int(**_void_**)**
968 : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
970 This procedure cannot fail.
972 **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
974 : Returns a random integer between **0** and *bound* (exclusive). Bias is
975 removed before returning the integer.
977 This procedure cannot fail.
979 ## Consumption and Propagation
981 Some functions are listed as consuming some or all of their arguments. This
982 means that the arguments are freed, regardless of if there were errors or not.
984 This is to enable compact code like the following:
986 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
988 If arguments to those functions were not consumed, memory would be leaked until
989 reclaimed with **bcl_ctxt_freeNums(BclContext)**.
991 When errors occur, they are propagated through. The result should always be
992 checked with **bcl_err(BclNumber)**, so the example above should properly
995 BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
996 if (bc_num_err(n) != BCL_ERROR_NONE) {
1002 Most functions in bcl(3) return, directly or indirectly, any one of the error
1003 codes defined in **BclError**. The complete list of codes is the following:
1007 : Success; no error occurred.
1009 **BCL_ERROR_INVALID_NUM**
1011 : An invalid **BclNumber** was given as a parameter.
1013 **BCL_ERROR_INVALID_CONTEXT**
1015 : An invalid **BclContext** is being used.
1017 **BCL_ERROR_SIGNAL**
1019 : A signal interrupted execution.
1021 **BCL_ERROR_MATH_NEGATIVE**
1023 : A negative number was given as an argument to a parameter that cannot accept
1024 negative numbers, such as for square roots.
1026 **BCL_ERROR_MATH_NON_INTEGER**
1028 : A non-integer was given as an argument to a parameter that cannot accept
1029 non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
1031 **BCL_ERROR_MATH_OVERFLOW**
1033 : A number that would overflow its result was given as an argument, such as
1034 for converting a **BclNumber** to a **BclBigDig**.
1036 **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
1038 : A divide by zero occurred.
1040 **BCL_ERROR_PARSE_INVALID_STR**
1042 : An invalid number string was passed to a parsing function.
1044 A valid number string can only be one radix (period). In addition, any
1045 lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
1046 allowed for the first character to be a dash. In that case, the number is
1047 considered to be negative.
1049 There is one exception to the above: one lowercase **e** is allowed in the
1050 number, after the radix, if it exists. If the letter **e** exists, the
1051 number is considered to be in scientific notation, where the part before the
1052 **e** is the number, and the part after, which must be an integer, is the
1053 exponent. There can be a dash right after the **e** to indicate a negative
1056 **WARNING**: Both the number and the exponent in scientific notation are
1057 interpreted according to the current **ibase**, but the number is still
1058 multiplied by **10\^exponent** regardless of the current **ibase**. For
1059 example, if **ibase** is **16** and bcl(3) is given the number string
1060 **FFeA**, the resulting decimal number will be **2550000000000**, and if
1061 bcl(3) is given the number string **10e-4**, the resulting decimal number
1064 **BCL_ERROR_FATAL_ALLOC_ERR**
1066 : bcl(3) failed to allocate memory.
1068 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1069 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1070 be turned off later by calling that same function with a **false** argument.
1071 By default, this behavior is off.
1073 It is highly recommended that client libraries do *not* activate this
1076 **BCL_ERROR_FATAL_UNKNOWN_ERR**
1078 : An unknown error occurred.
1080 If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
1081 this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
1082 be turned off later by calling that same function with a **false** argument.
1083 By default, this behavior is off.
1085 It is highly recommended that client libraries do *not* activate this
1090 When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is
1093 bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
1098 Most bc(1) implementations use **char** types to calculate the value of **1**
1099 decimal digit at a time, but that can be slow. bcl(3) does something
1102 It uses large integers to calculate more than **1** decimal digit at a time. If
1103 built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1104 **64**, then each integer has **9** decimal digits. If built in an environment
1105 where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1106 value (the number of decimal digits per large integer) is called
1109 In addition, this bcl(3) uses an even larger integer for overflow checking. This
1110 integer type depends on the value of **BC_LONG_BIT**, but is always at least
1111 twice as large as the integer type used to store digits.
1115 The following are the limits on bcl(3):
1119 : The number of bits in the **long** type in the environment where bcl(3) was
1120 built. This determines how many decimal digits can be stored in a single
1121 large integer (see the **PERFORMANCE** section).
1125 : The number of decimal digits per large integer (see the **PERFORMANCE**
1126 section). Depends on **BC_LONG_BIT**.
1130 : The max decimal number that each large integer can store (see
1131 **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1135 : The max number that the overflow type (see the **PERFORMANCE** section) can
1136 hold. Depends on **BC_LONG_BIT**.
1140 : The maximum output base. Set at **BC_BASE_POW**.
1144 : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1148 : The maximum length of a number (in decimal digits), which includes digits
1149 after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1153 : The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
1154 Set at **2\^BC_LONG_BIT-1**.
1158 : The maximum allowable exponent (positive or negative). Set at
1159 **BC_OVERFLOW_MAX**.
1161 These limits are meant to be effectively non-existent; the limits are so large
1162 (at least on 64-bit machines) that there should not be any point at which they
1163 become a problem. In fact, memory should be exhausted before these limits should
1168 If a signal handler calls **bcl_handleSignal(**_void_**)** from the same thread
1169 that there are bcl(3) functions executing in, it will cause all execution to
1170 stop as soon as possible, interrupting long-running calculations, if necessary
1171 and cause the function that was executing to return. If possible, the error code
1172 **BC_ERROR_SIGNAL** is returned.
1174 If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
1175 return to its caller.
1177 It is undefined behavior if **bcl_handleSignal(**_void_**)** is called from
1178 a thread that is not executing bcl(3) functions, if bcl(3) functions are
1187 bcl(3) is compliant with the arithmetic defined in the
1188 [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification for bc(1).
1190 Note that the specification explicitly says that bc(1) only accepts numbers that
1191 use a period (**.**) as a radix point, regardless of the value of
1192 **LC_NUMERIC**. This is also true of bcl(3).
1196 None are known. Report bugs at https://git.yzena.com/gavin/bc.
1200 Gavin D. Howard <gavin@yzena.com> and contributors.
1202 [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html