bignum_ig/lib.rs
1//! # Big Number
2//!
3//! `bignum-ig` is a crate that supplies a Big Number Type [Big], which allows expressing
4//! much larger or smaller numbers than [prim@f64] can do. This is done through an extra [prim@i64] exponent
5//! field to increase the exponent range.
6//!
7//! [Big] has the same precision as a [prim@f64] and the same floating point arithmetic quirks.
8//! The primary use of this crate is for [Incremental Games](https://en.wikipedia.org/wiki/Incremental_game),
9//! a game genre which can feature very large numbers.
10
11use std::{
12 f64,
13 fmt::Display,
14 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
15};
16
17mod comparison;
18mod conversion;
19mod fmt_simple;
20#[cfg(test)]
21mod tests;
22
23/// # The Big Number Type
24///
25/// A Number in the range of 10<sup>[i64::MIN]</sup>..10.0*10<sup>[i64::MAX]</sup> (exclusive).
26///
27/// # Basic Usage
28///
29/// Create Numbers using [Big::new()] and [Big::from()].
30///
31/// Operate on these numbers with regular operators: +, -, *, /
32#[derive(Debug, Clone)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub enum Big {
35 /// A normal number in the form of Mantissa * 10<sup>Exponent</sup>
36 Number {
37 /// Mantissa, ranging from 1.0 to 10.0 exclusively
38 m: f64,
39 /// Exponent
40 e: i64,
41 },
42 /// Not a Number, never equal to itself
43 NaN,
44 /// Positive or Negative Infinity
45 Infinity(InfinityKind),
46 /// ± 0
47 Zero,
48}
49
50/// This type is used to describe if an Infinity is positive or negative.
51/// You will rarely use it yourself. You should look at [Big::is_pos_inf()] and [Big::is_neg_inf()] instead
52/// There are also [crate::POS_INFINITY] and [crate::NEG_INFINITY] for ease of use.
53#[derive(Debug, PartialEq, Clone)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub enum InfinityKind {
56 /// Positive Infinity, also referred to as +inf
57 Positive,
58 /// Negative Infinity, also referred to as -inf
59 Negative,
60}
61
62/// A Constant Describing Positive Infinity
63pub const POS_INFINITY: Big = Big::Infinity(InfinityKind::Positive);
64/// A Constant Describing Negative Infinity
65pub const NEG_INFINITY: Big = Big::Infinity(InfinityKind::Negative);
66const SIG_DIGITS: i64 = 15;
67
68impl Big {
69 /// Create a new Instance. The Number is normalized automatically.
70 ///
71 /// # Example
72 /// ```
73 /// use bignum_ig::Big;
74 ///
75 /// let number = Big::new(1.0, 1);
76 /// assert_eq!(number, Big::new(10.0, 0));
77 /// ```
78 pub fn new(mantissa: f64, exponent: i64) -> Self {
79 let mut number = Self::Number {
80 m: mantissa,
81 e: exponent,
82 };
83 number.normalize();
84 number
85 }
86
87 /// Create a new Instance, skipping normalization
88 ///
89 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
90 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
91 ///
92 /// You will most likely want to use Big::new or Big::From instead
93 pub fn new_unnormalized(mantissa: f64, exponent: i64) -> Self {
94 Self::Number {
95 m: mantissa,
96 e: exponent,
97 }
98 }
99
100 /// Normalize the number so it is in a correct state.
101 ///
102 /// **Note:** Unless you used any `_unnormalized` method, you never need to call this manually.
103 pub fn normalize(&mut self) {
104 match *self {
105 Self::Infinity(_) | Self::NaN | Self::Zero => return,
106 Self::Number { m, .. } => match m {
107 m if m == 0.0 => {
108 *self = Self::Zero;
109 return;
110 }
111 m if m.is_nan() => {
112 *self = Self::NaN;
113 return;
114 }
115 m if m == f64::INFINITY => {
116 *self = POS_INFINITY;
117 return;
118 }
119 m if m == f64::NEG_INFINITY => {
120 *self = NEG_INFINITY;
121 return;
122 }
123 // if the number is already normalized, we can skip everything below
124 m if (1.0..10.0).contains(&m) => return,
125 // see below
126 _ => {}
127 },
128 };
129
130 if let Self::Number {
131 ref mut m,
132 ref mut e,
133 } = *self
134 {
135 let log = m.abs().log10() as i64;
136
137 match log {
138 // might underflow to Zero
139 ..=0 => {
140 if e.checked_sub(-log).is_none() {
141 *self = Self::Zero;
142 return;
143 }
144 }
145 // might overflow to either positive or negative Infinity (+inf; -inf)
146 _positive => {
147 if e.checked_add(log).is_none() {
148 match m.is_sign_positive() {
149 true => *self = POS_INFINITY,
150 false => *self = NEG_INFINITY,
151 };
152 return;
153 }
154 }
155 }
156
157 let log = m.abs().log10().floor() as i64;
158 *m /= 10.0_f64.powi(log as i32);
159 *e += log;
160 }
161 }
162
163 /// This will invert the sign of `self`, modifying it in-place.
164 ///
165 /// # Example
166 /// ```
167 /// use bignum_ig::Big;
168 ///
169 /// let mut number = Big::from(42);
170 /// number.neg_mut();
171 /// assert_eq!(number, Big::from(-42));
172 /// ```
173 pub fn neg_mut(&mut self) {
174 // normalization should not be required here
175 match self {
176 Self::Infinity(InfinityKind::Positive) => *self = NEG_INFINITY,
177 Self::Infinity(InfinityKind::Negative) => *self = POS_INFINITY,
178 Self::Number { m, .. } => {
179 *m *= -1.0;
180 }
181 _ => {}
182 }
183 }
184
185 /// This will add `rhs` to `self` without normalizing the result.
186 ///
187 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
188 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
189 ///
190 /// You will most likely want to use the += or + operator instead, which will normalize the result automatically.
191 pub fn add_mut_unnormalized(&mut self, rhs: Self) {
192 match (&self, &rhs) {
193 // NaN
194 (Self::NaN, _) | (_, Self::NaN) => *self = Self::NaN,
195
196 // Infinities
197
198 // +inf + -inf and -inf + +inf are undefined
199 (Self::Infinity(kind), Self::Infinity(kind2)) if kind != kind2 => *self = Self::NaN,
200 (Self::Infinity(_), Self::Infinity(_)) => return,
201
202 (Self::Infinity(_), Self::Number { .. } | Self::Zero) => {
203 return;
204 }
205 (Self::Number { .. } | Self::Zero, Self::Infinity(kind)) => {
206 *self = Self::Infinity(kind.clone())
207 }
208
209 // Zero
210 (Self::Zero, other) => {
211 *self = other.clone();
212 }
213 (Self::Number { .. }, Self::Zero) => return,
214
215 // see below
216 (Self::Number { .. }, Self::Number { .. }) => {}
217 }
218
219 // a + b
220 if let (
221 Self::Number { m, e },
222 Self::Number {
223 m: other_m,
224 e: other_e,
225 },
226 ) = (self, rhs)
227 {
228 let delta = other_e - *e;
229 match delta {
230 // ..=-SIG_DIGITS produced a syntax error
231 _delta if delta <= -SIG_DIGITS => {}
232 _delta if delta >= SIG_DIGITS => {
233 *m = other_m;
234 *e = other_e;
235 }
236 delta => {
237 let delta: i32 = delta.try_into().expect(
238 "exponent delta between a, b in a + b should never exceed 13
239 and can therefore be cast into i32",
240 );
241
242 *m += other_m * 10.0_f64.powi(delta);
243 }
244 }
245 };
246 }
247
248 /// This will substract `rhs` from `self` without normalizing the result.
249 ///
250 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
251 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
252 ///
253 /// You will most likely want to use the -= or - operator instead, which will normalize the result automatically.
254 pub fn sub_mut_unnormalized(&mut self, rhs: Self) {
255 match (&self, &rhs) {
256 // NaN
257 (Self::NaN, _) | (_, Self::NaN) => *self = Self::NaN,
258
259 // Infinities
260
261 // +inf - -inf and -inf - +inf are undefined
262 (Self::Infinity(_), Self::Infinity(_)) => *self = Self::NaN,
263
264 (Self::Infinity(_), Self::Number { .. } | Self::Zero) => {
265 return;
266 }
267 (Self::Number { .. } | Self::Zero, Self::Infinity(InfinityKind::Positive)) => {
268 *self = NEG_INFINITY;
269 }
270 (Self::Number { .. } | Self::Zero, Self::Infinity(InfinityKind::Negative)) => {
271 *self = POS_INFINITY;
272 }
273
274 // Zero
275 (Self::Zero, other) => {
276 *self = other.clone();
277 self.neg_mut();
278 }
279 (Self::Number { .. }, Self::Zero) => return,
280
281 // see below
282 (Self::Number { .. }, Self::Number { .. }) => {}
283 }
284
285 // a - b
286 if let (
287 Self::Number { m, e },
288 Self::Number {
289 m: other_m,
290 e: other_e,
291 },
292 ) = (self, rhs)
293 {
294 let delta = other_e - *e;
295 match delta {
296 // ..=-SIG_DIGITS produced a syntax error
297 _delta if delta <= -SIG_DIGITS => {}
298 _delta if delta >= SIG_DIGITS => {
299 *m = other_m;
300 *e = other_e;
301 }
302 delta => {
303 let delta: i32 = delta.try_into().expect(
304 "exponent delta between a, b in a - b should never exceed 13
305 and can therefore be cast into i32",
306 );
307
308 *m -= other_m * 10.0_f64.powi(delta);
309 }
310 }
311 };
312 }
313
314 /// This will multiply `rhs` onto `self` without normalizing the result.
315 ///
316 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
317 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
318 ///
319 /// You will most likely want to use the *= or * operator instead, which will normalize the result automatically.
320 pub fn mul_mut_unnormalized(&mut self, rhs: Self) {
321 match (&self, &rhs) {
322 // NaN
323 (Self::NaN, _) | (_, Self::NaN) => *self = Self::NaN,
324
325 // Infinities
326 (Self::Infinity(_), Self::Infinity(InfinityKind::Positive)) => return,
327 (_, Self::Infinity(InfinityKind::Negative)) => *self = NEG_INFINITY,
328 (Self::Zero, Self::Infinity(_)) | (Self::Infinity(_), Self::Zero) => *self = Self::NaN,
329 (Self::Number { .. }, Self::Infinity(kind)) => *self = Self::Infinity(kind.clone()),
330 (Self::Infinity(_), Self::Number { .. }) => return,
331
332 // Zero
333 (Self::Zero, _) => return,
334 (Self::Number { .. }, Self::Zero) => *self = Self::Zero,
335
336 // see below
337 (Self::Number { .. }, Self::Number { .. }) => {}
338 }
339
340 // a * b
341 if let (
342 Self::Number { m, e },
343 Self::Number {
344 m: other_m,
345 e: other_e,
346 },
347 ) = (self, rhs)
348 {
349 *m *= other_m;
350 *e += other_e;
351 };
352 }
353
354 /// This will divide `rhs` from `self` without normalizing the result.
355 ///
356 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
357 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
358 ///
359 /// You will most likely want to use the /= or / operator instead, which will normalize the result automatically.
360 pub fn div_mut_unnormalized(&mut self, rhs: Self) {
361 match (&self, &rhs) {
362 // NaN
363 (Self::NaN, _) | (_, Self::NaN) => *self = Self::NaN,
364
365 // Infinities
366 (Self::Infinity(_), Self::Infinity(_)) => *self = Self::NaN,
367 (Self::Number { .. } | Self::Zero, Self::Infinity(_)) => *self = Self::Zero,
368 (Self::Infinity(_), Self::Number { .. }) => return,
369
370 // Zero
371 (Self::Zero, _) => return,
372 (_, Self::Zero) => *self = Self::NaN,
373
374 // see below
375 (Self::Number { .. }, Self::Number { .. }) => {}
376 }
377
378 // a / b
379 if let (
380 Self::Number { m, e },
381 Self::Number {
382 m: other_m,
383 e: other_e,
384 },
385 ) = (self, rhs)
386 {
387 *m /= other_m;
388 *e -= other_e;
389 };
390 }
391
392 /// Take the absolute value of `self`, modifying it in-place
393 ///
394 /// # Example
395 /// ```
396 /// use bignum_ig::Big;
397 ///
398 /// let mut number = Big::from(-42);
399 /// number.abs_mut();
400 /// assert_eq!(number, Big::from(42));
401 /// ```
402 pub fn abs_mut(&mut self) {
403 if let Self::Number { m, .. } = self {
404 *m = m.abs();
405 }
406 }
407
408 /// Take the absolute value of `self`, creating a new Instance
409 ///
410 /// # Example
411 /// ```
412 /// use bignum_ig::Big;
413 ///
414 /// assert_eq!(Big::from(-42).abs(), Big::from(42));
415 /// assert_eq!(Big::from(42).abs(), Big::from(42));
416 /// ```
417 pub fn abs(&self) -> Self {
418 let mut result = self.clone();
419 result.abs_mut();
420 result
421 }
422
423 /// Return true if `self` is NaN
424 ///
425 /// Use this method because [Big::NaN] != [Big::NaN]
426 ///
427 /// # Example
428 /// ```
429 /// use bignum_ig::Big;
430 ///
431 /// assert!(Big::NaN.is_nan());
432 /// ```
433 pub fn is_nan(&self) -> bool {
434 matches!(self, Self::NaN)
435 }
436
437 /// Return true if `self` is +inf
438 ///
439 /// Use this method because +inf != +inf
440 ///
441 /// # Example
442 /// ```
443 /// assert!(bignum_ig::POS_INFINITY.is_pos_inf());
444 /// ```
445 pub fn is_pos_inf(&self) -> bool {
446 matches!(self, Self::Infinity(InfinityKind::Positive))
447 }
448
449 /// Return true if `self` is -inf
450 ///
451 /// Use this method because -inf != -inf
452 ///
453 /// # Example
454 /// ```
455 /// assert!(bignum_ig::NEG_INFINITY.is_neg_inf());
456 /// ```
457 pub fn is_neg_inf(&self) -> bool {
458 matches!(self, Self::Infinity(InfinityKind::Negative))
459 }
460
461 /// Return true if `self` is Zero
462 ///
463 /// Comparing `self` to [Big::Zero] is also possible
464 ///
465 /// # Example
466 /// ```
467 /// use bignum_ig::Big;
468 ///
469 /// assert!(Big::from(0).is_zero());
470 /// ```
471 pub fn is_zero(&self) -> bool {
472 self == &Big::Zero
473 }
474
475 /// Return the logarithm to the base of 10 of `self`
476 ///
477 /// # Example
478 /// ```
479 /// use bignum_ig::Big;
480 ///
481 /// let log = Big::from(100).log10();
482 /// assert_eq!(log, 2.0);
483 /// ```
484 pub fn log10(self) -> f64 {
485 match self {
486 Self::Number { m, e } => m.log10() + e as f64,
487 Self::Infinity(InfinityKind::Negative) => f64::NAN,
488 Self::Infinity(InfinityKind::Positive) => f64::INFINITY,
489 Self::Zero | Self::NaN => f64::NAN,
490 }
491 }
492
493 /// Return the natural logarithm of `self`
494 ///
495 /// # Example
496 /// ```
497 /// use bignum_ig::Big;
498 ///
499 /// let ln = Big::from(f64::exp(2.0)).ln();
500 /// assert_eq!(ln, 2.0);
501 /// ```
502 pub fn ln(self) -> f64 {
503 match self.log10() {
504 log if log.is_normal() => log / f64::consts::LOG10_E,
505 log => log,
506 }
507 }
508
509 /// Return the logarithm of any base of `self`
510 ///
511 /// # Example
512 /// ```
513 /// use bignum_ig::Big;
514 ///
515 /// let log = Big::from(256).log(16.0);
516 /// assert_eq!(log, 2.0);
517 /// ```
518 pub fn log(self, base: f64) -> f64 {
519 if base.is_normal() {
520 self.ln() / base.ln()
521 } else {
522 f64::NAN
523 }
524 }
525
526 /// Raise `self` to `power` and modify it in-place.
527 ///
528 /// # Example
529 /// ```
530 /// use bignum_ig::Big;
531 ///
532 /// let mut number = Big::from(16);
533 /// number.powf_mut(2.0);
534 /// assert_eq!(number, Big::from(256));
535 /// ```
536 pub fn powf_mut(&mut self, power: f64) {
537 if let Self::Zero = self {
538 if power.is_normal() {
539 return;
540 }
541 }
542
543 let result_log10 = self.abs().log10() * power;
544
545 match result_log10 {
546 f64::NEG_INFINITY => *self = Self::NaN,
547 f64::INFINITY => *self = POS_INFINITY,
548 log if log.is_nan() => *self = Self::NaN,
549 // result_log10 may over/underflow as an i64, handle it
550 log if log < i64::MIN as f64 => *self = Self::Zero,
551 log if log > i64::MAX as f64 => *self = POS_INFINITY,
552 // normaliazion shouldn't be required here, since m will be between 1.0 and < 10.0
553 log => {
554 if let Self::Number { m, e } = self {
555 *m = 10.0_f64.powf(log % 1.0);
556 // minus times minus is plus
557 if log % 2.0 == 0.0 {
558 *m = m.abs();
559 }
560 *e = log as i64;
561 }
562 }
563 };
564 }
565
566 /// Raise `self` to `power`, returning a new Instance
567 ///
568 /// # Example
569 /// ```
570 /// use bignum_ig::Big;
571 ///
572 /// assert_eq!(Big::from(16).powf(2.0), Big::from(256));
573 /// ```
574 pub fn powf(&self, power: f64) -> Self {
575 let mut result = self.clone();
576 result.powf_mut(power);
577 result
578 }
579
580 /// This will put the remainder of `self` % `rhs` into `self` without normalizing the result.
581 ///
582 /// **Caution:** Only use this if you are absolutely sure of what you are doing and need every bit of performance!
583 /// You will have to call [Big::normalize()] yourself at some point to prevent bugs.
584 ///
585 /// You will most likely want to use the %= or % operator instead, which will normalize the result automatically.
586 pub fn remainder_mut_unnormalized(&mut self, rhs: &Big) {
587 match (&self, rhs) {
588 (Self::NaN, _) | (_, Self::NaN) => return,
589 (_, Self::Zero) => *self = Self::NaN,
590 (Self::Infinity(_), Self::Infinity(_)) => *self = Self::NaN,
591 (Self::Zero, _) => return,
592 (Self::Number { .. }, Self::Infinity(_)) => return,
593 (Self::Infinity(_), Self::Number { .. }) => *self = Self::NaN,
594 // See below
595 (Self::Number { .. }, Self::Number { .. }) => {}
596 }
597
598 if let (
599 Self::Number { m, e },
600 Self::Number {
601 m: other_m,
602 e: other_e,
603 },
604 ) = (self, rhs)
605 {
606 let other_m_normalized = other_m * 10_f64.powi((*other_e - *e) as i32);
607 *m = match other_m_normalized {
608 f64::INFINITY => *m,
609 0.0 => 0.0,
610 value => *m % value,
611 }
612 }
613 }
614}
615
616impl AddAssign for Big {
617 fn add_assign(&mut self, rhs: Self) {
618 self.add_mut_unnormalized(rhs);
619 self.normalize();
620 }
621}
622
623impl Add for Big {
624 type Output = Big;
625
626 fn add(self, rhs: Self) -> Self::Output {
627 let mut result = self.clone();
628 result += rhs;
629 result
630 }
631}
632
633impl SubAssign for Big {
634 fn sub_assign(&mut self, rhs: Self) {
635 self.sub_mut_unnormalized(rhs);
636 self.normalize();
637 }
638}
639
640impl Sub for Big {
641 type Output = Big;
642
643 fn sub(self, rhs: Self) -> Self::Output {
644 let mut result = self.clone();
645 result -= rhs;
646 result
647 }
648}
649
650impl MulAssign for Big {
651 fn mul_assign(&mut self, rhs: Self) {
652 self.mul_mut_unnormalized(rhs);
653 self.normalize();
654 }
655}
656
657impl Mul for Big {
658 type Output = Big;
659
660 fn mul(self, rhs: Self) -> Self::Output {
661 let mut result = self.clone();
662 result *= rhs;
663 result
664 }
665}
666
667impl DivAssign for Big {
668 fn div_assign(&mut self, rhs: Self) {
669 self.div_mut_unnormalized(rhs);
670 self.normalize();
671 }
672}
673
674impl Div for Big {
675 type Output = Big;
676
677 fn div(self, rhs: Self) -> Self::Output {
678 let mut result = self.clone();
679 result /= rhs;
680 result
681 }
682}
683
684impl RemAssign for Big {
685 fn rem_assign(&mut self, rhs: Self) {
686 self.remainder_mut_unnormalized(&rhs);
687 self.normalize();
688 }
689}
690
691impl Rem for Big {
692 type Output = Big;
693
694 fn rem(self, rhs: Self) -> Self::Output {
695 let mut result = self.clone();
696 result %= rhs;
697 result
698 }
699}
700
701impl Neg for Big {
702 type Output = Big;
703
704 fn neg(self) -> Self::Output {
705 let mut result = self.clone();
706 result.neg_mut();
707 result
708 }
709}
710
711impl Display for Big {
712 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713 match self {
714 Big::Infinity(kind) => match kind {
715 InfinityKind::Positive => write!(f, "+inf"),
716 InfinityKind::Negative => write!(f, "-inf"),
717 },
718 Big::NaN => write!(f, "NaN"),
719 Big::Zero => write!(f, "0"),
720 Big::Number { m, e } => write!(f, "{}e{}", m, e),
721 }
722 }
723}