-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathlib.rs
3485 lines (3052 loc) · 106 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Adam Sunderland
// 2016-2023 Andrew Kubera
// 2017 Ruben De Smet
// See the COPYRIGHT file at the top-level directory of this
// distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A Big Decimal
//!
//! `BigDecimal` allows storing any real number to arbitrary precision; which
//! avoids common floating point errors (such as 0.1 + 0.2 ≠ 0.3) at the
//! cost of complexity.
//!
//! Internally, `BigDecimal` uses a `BigInt` object, paired with a 64-bit
//! integer which determines the position of the decimal point. Therefore,
//! the precision *is not* actually arbitrary, but limited to 2<sup>63</sup>
//! decimal places.
//!
//! Common numerical operations are overloaded, so we can treat them
//! the same way we treat other numbers.
//!
//! It is not recommended to convert a floating point number to a decimal
//! directly, as the floating point representation may be unexpected.
//!
//! # Example
//!
//! ```
//! use bigdecimal::BigDecimal;
//! use std::str::FromStr;
//!
//! let input = "0.8";
//! let dec = BigDecimal::from_str(&input).unwrap();
//! let float = f32::from_str(&input).unwrap();
//!
//! println!("Input ({}) with 10 decimals: {} vs {})", input, dec, float);
//! ```
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::style)]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::needless_return)]
#![allow(clippy::suspicious_arithmetic_impl)]
#![allow(clippy::suspicious_op_assign_impl)]
#![allow(clippy::redundant_field_names)]
pub extern crate num_bigint;
pub extern crate num_traits;
extern crate num_integer;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "std")]
include!("./with_std.rs");
#[cfg(not(feature = "std"))]
include!("./without_std.rs");
// make available some standard items
use self::stdlib::cmp::{self, Ordering};
use self::stdlib::convert::TryFrom;
use self::stdlib::default::Default;
use self::stdlib::hash::{Hash, Hasher};
use self::stdlib::num::{ParseFloatError, ParseIntError};
use self::stdlib::ops::{Add, AddAssign, Div, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
use self::stdlib::iter::Sum;
use self::stdlib::str::FromStr;
use self::stdlib::string::{String, ToString};
use self::stdlib::fmt;
use num_bigint::{BigInt, ParseBigIntError, Sign, ToBigInt};
use num_integer::Integer as IntegerTrait;
pub use num_traits::{FromPrimitive, Num, One, Signed, ToPrimitive, Zero};
#[allow(clippy::approx_constant)] // requires Rust 1.43.0
const LOG2_10: f64 = 3.321928094887362_f64;
// const DEFAULT_PRECISION: u64 = ${RUST_BIGDECIMAL_DEFAULT_PRECISION} or 100;
include!(concat!(env!("OUT_DIR"), "/default_precision.rs"));
#[macro_use]
mod macros;
#[cfg(test)]
extern crate paste;
mod parsing;
pub mod rounding;
pub use rounding::RoundingMode;
#[inline(always)]
fn ten_to_the(pow: u64) -> BigInt {
if pow < 20 {
BigInt::from(10u64.pow(pow as u32))
} else {
let (half, rem) = pow.div_rem(&16);
let mut x = ten_to_the(half);
for _ in 0..4 {
x = &x * &x;
}
if rem == 0 {
x
} else {
x * ten_to_the(rem)
}
}
}
#[inline(always)]
fn count_decimal_digits(int: &BigInt) -> u64 {
if int.is_zero() {
return 1;
}
let uint = int.magnitude();
let mut digits = (uint.bits() as f64 / LOG2_10) as u64;
// guess number of digits based on number of bits in UInt
let mut num = ten_to_the(digits).to_biguint().expect("Ten to power is negative");
while *uint >= num {
num *= 10u8;
digits += 1;
}
digits
}
/// Internal function used for rounding
///
/// returns 1 if most significant digit is >= 5, otherwise 0
///
/// This is used after dividing a number by a power of ten and
/// rounding the last digit.
///
#[inline(always)]
fn get_rounding_term(num: &BigInt) -> u8 {
if num.is_zero() {
return 0;
}
let digits = (num.bits() as f64 / LOG2_10) as u64;
let mut n = ten_to_the(digits);
// loop-method
loop {
if *num < n {
return 1;
}
n *= 5;
if *num < n {
return 0;
}
n *= 2;
}
// string-method
// let s = format!("{}", num);
// let high_digit = u8::from_str(&s[0..1]).unwrap();
// if high_digit < 5 { 0 } else { 1 }
}
/// A big decimal type.
///
#[derive(Clone, Eq)]
pub struct BigDecimal {
int_val: BigInt,
// A positive scale means a negative power of 10
scale: i64,
}
#[cfg(not(feature = "std"))]
// f64::exp2 is only available in std, we have to use an external crate like libm
fn exp2(x: f64) -> f64 {
libm::exp2(x)
}
#[cfg(feature = "std")]
fn exp2(x: f64) -> f64 {
x.exp2()
}
impl BigDecimal {
/// Creates and initializes a `BigDecimal`.
///
#[inline]
pub fn new(digits: BigInt, scale: i64) -> BigDecimal {
BigDecimal {
int_val: digits,
scale: scale,
}
}
/// Creates and initializes a `BigDecimal`.
///
/// Decodes using `str::from_utf8` and forwards to `BigDecimal::from_str_radix`.
/// Only base-10 is supported.
///
/// # Examples
///
/// ```
/// use bigdecimal::{BigDecimal, Zero};
///
/// assert_eq!(BigDecimal::parse_bytes(b"0", 10).unwrap(), BigDecimal::zero());
/// assert_eq!(BigDecimal::parse_bytes(b"13", 10).unwrap(), BigDecimal::from(13));
/// ```
#[inline]
pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigDecimal> {
stdlib::str::from_utf8(buf)
.ok()
.and_then(|s| BigDecimal::from_str_radix(s, radix).ok())
}
/// Return a new BigDecimal object equivalent to self, with internal
/// scaling set to the number specified.
/// If the new_scale is lower than the current value (indicating a larger
/// power of 10), digits will be dropped (as precision is lower)
///
#[inline]
pub fn with_scale(&self, new_scale: i64) -> BigDecimal {
if self.int_val.is_zero() {
return BigDecimal::new(BigInt::zero(), new_scale);
}
match new_scale.cmp(&self.scale) {
Ordering::Greater => {
let scale_diff = new_scale - self.scale;
let int_val = &self.int_val * ten_to_the(scale_diff as u64);
BigDecimal::new(int_val, new_scale)
}
Ordering::Less => {
let scale_diff = self.scale - new_scale;
let int_val = &self.int_val / ten_to_the(scale_diff as u64);
BigDecimal::new(int_val, new_scale)
}
Ordering::Equal => self.clone(),
}
}
/// Return a new BigDecimal after shortening the digits and rounding
///
/// ```
/// # use bigdecimal::*;
///
/// let n: BigDecimal = "129.41675".parse().unwrap();
///
/// assert_eq!(n.with_scale_round(2, RoundingMode::Up), "129.42".parse().unwrap());
/// assert_eq!(n.with_scale_round(-1, RoundingMode::Down), "120".parse().unwrap());
/// assert_eq!(n.with_scale_round(4, RoundingMode::HalfEven), "129.4168".parse().unwrap());
/// ```
pub fn with_scale_round(&self, new_scale: i64, mode: RoundingMode) -> BigDecimal {
use stdlib::cmp::Ordering::*;
if self.int_val.is_zero() {
return BigDecimal::new(BigInt::zero(), new_scale);
}
match new_scale.cmp(&self.scale) {
Ordering::Equal => {
self.clone()
}
Ordering::Greater => {
// increase number of zeros
let scale_diff = new_scale - self.scale;
let int_val = &self.int_val * ten_to_the(scale_diff as u64);
BigDecimal::new(int_val, new_scale)
}
Ordering::Less => {
let (sign, mut digits) = self.int_val.to_radix_le(10);
let digit_count = digits.len();
let int_digit_count = digit_count as i64 - self.scale;
let rounded_int = match int_digit_count.cmp(&-new_scale) {
Equal => {
let (&last_digit, remaining) = digits.split_last().unwrap();
let trailing_zeros = remaining.iter().all(Zero::is_zero);
let rounded_digit = mode.round_pair(sign, (0, last_digit), trailing_zeros);
BigInt::new(sign, vec![rounded_digit as u32])
}
Less => {
debug_assert!(!digits.iter().all(Zero::is_zero));
let rounded_digit = mode.round_pair(sign, (0, 0), false);
BigInt::new(sign, vec![rounded_digit as u32])
}
Greater => {
// location of new rounding point
let scale_diff = (self.scale - new_scale) as usize;
let low_digit = digits[scale_diff - 1];
let high_digit = digits[scale_diff];
let trailing_zeros = digits[0..scale_diff-1].iter().all(Zero::is_zero);
let rounded_digit = mode.round_pair(sign, (high_digit, low_digit), trailing_zeros);
debug_assert!(rounded_digit <= 10);
if rounded_digit < 10 {
digits[scale_diff] = rounded_digit;
} else {
digits[scale_diff] = 0;
let mut i = scale_diff + 1;
loop {
if i == digit_count {
digits.push(1);
break;
}
if digits[i] < 9 {
digits[i] += 1;
break;
}
digits[i] = 0;
i += 1;
}
}
BigInt::from_radix_le(sign, &digits[scale_diff..], 10).unwrap()
}
};
BigDecimal::new(rounded_int, new_scale)
}
}
}
/// Return a new BigDecimal object with same value and given scale,
/// padding with zeros or truncating digits as needed
///
/// Useful for aligning decimals before adding/subtracting.
///
fn take_and_scale(mut self, new_scale: i64) -> BigDecimal {
if self.int_val.is_zero() {
return BigDecimal::new(BigInt::zero(), new_scale);
}
match new_scale.cmp(&self.scale) {
Ordering::Greater => {
self.int_val *= ten_to_the((new_scale - self.scale) as u64);
BigDecimal::new(self.int_val, new_scale)
}
Ordering::Less => {
self.int_val /= ten_to_the((self.scale - new_scale) as u64);
BigDecimal::new(self.int_val, new_scale)
}
Ordering::Equal => self,
}
}
/// Return a new BigDecimal object with precision set to new value
///
/// ```
/// # use bigdecimal::*;
///
/// let n: BigDecimal = "129.41675".parse().unwrap();
///
/// assert_eq!(n.with_prec(2), "130".parse().unwrap());
///
/// let n_p12 = n.with_prec(12);
/// let (i, scale) = n_p12.as_bigint_and_exponent();
/// assert_eq!(n_p12, "129.416750000".parse().unwrap());
/// assert_eq!(i, 129416750000_u64.into());
/// assert_eq!(scale, 9);
/// ```
pub fn with_prec(&self, prec: u64) -> BigDecimal {
let digits = self.digits();
match digits.cmp(&prec) {
Ordering::Greater => {
let diff = digits - prec;
let p = ten_to_the(diff);
let (mut q, r) = self.int_val.div_rem(&p);
// check for "leading zero" in remainder term; otherwise round
if p < 10 * &r {
q += get_rounding_term(&r);
}
BigDecimal {
int_val: q,
scale: self.scale - diff as i64,
}
}
Ordering::Less => {
let diff = prec - digits;
BigDecimal {
int_val: &self.int_val * ten_to_the(diff),
scale: self.scale + diff as i64,
}
}
Ordering::Equal => self.clone(),
}
}
/// Return the sign of the `BigDecimal` as `num::bigint::Sign`.
///
/// ```
/// # use bigdecimal::{BigDecimal, num_bigint::Sign};
///
/// fn sign_of(src: &str) -> Sign {
/// let n: BigDecimal = src.parse().unwrap();
/// n.sign()
/// }
///
/// assert_eq!(sign_of("-1"), Sign::Minus);
/// assert_eq!(sign_of("0"), Sign::NoSign);
/// assert_eq!(sign_of("1"), Sign::Plus);
/// ```
#[inline]
pub fn sign(&self) -> num_bigint::Sign {
self.int_val.sign()
}
/// Return the internal big integer value and an exponent. Note that a positive
/// exponent indicates a negative power of 10.
///
/// # Examples
///
/// ```
/// use bigdecimal::{BigDecimal, num_bigint::BigInt};
///
/// let n: BigDecimal = "1.23456".parse().unwrap();
/// let expected = ("123456".parse::<BigInt>().unwrap(), 5);
/// assert_eq!(n.as_bigint_and_exponent(), expected);
/// ```
#[inline]
pub fn as_bigint_and_exponent(&self) -> (BigInt, i64) {
(self.int_val.clone(), self.scale)
}
/// Convert into the internal big integer value and an exponent. Note that a positive
/// exponent indicates a negative power of 10.
///
/// # Examples
///
/// ```
/// use bigdecimal::{BigDecimal, num_bigint::BigInt};
///
/// let n: BigDecimal = "1.23456".parse().unwrap();
/// let expected = ("123456".parse::<num_bigint::BigInt>().unwrap(), 5);
/// assert_eq!(n.into_bigint_and_exponent(), expected);
/// ```
#[inline]
pub fn into_bigint_and_exponent(self) -> (BigInt, i64) {
(self.int_val, self.scale)
}
/// Number of digits in the non-scaled integer representation
///
#[inline]
pub fn digits(&self) -> u64 {
count_decimal_digits(&self.int_val)
}
/// Compute the absolute value of number
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "123.45".parse().unwrap();
/// assert_eq!(n.abs(), "123.45".parse().unwrap());
///
/// let n: BigDecimal = "-123.45".parse().unwrap();
/// assert_eq!(n.abs(), "123.45".parse().unwrap());
/// ```
#[inline]
pub fn abs(&self) -> BigDecimal {
BigDecimal {
int_val: self.int_val.abs(),
scale: self.scale,
}
}
/// Multiply decimal by 2 (efficiently)
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "123.45".parse().unwrap();
/// assert_eq!(n.double(), "246.90".parse().unwrap());
/// ```
pub fn double(&self) -> BigDecimal {
if self.is_zero() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * 2,
scale: self.scale,
}
}
}
/// Divide decimal by 2 (efficiently)
///
/// *Note*: If the last digit in the decimal is odd, the precision
/// will increase by 1
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "123.45".parse().unwrap();
/// assert_eq!(n.half(), "61.725".parse().unwrap());
/// ```
#[inline]
pub fn half(&self) -> BigDecimal {
if self.is_zero() {
self.clone()
} else if self.int_val.is_even() {
BigDecimal {
int_val: self.int_val.clone().div(2u8),
scale: self.scale,
}
} else {
BigDecimal {
int_val: self.int_val.clone().mul(5u8),
scale: self.scale + 1,
}
}
}
/// Square a decimal: *x²*
///
/// No rounding or truncating of digits; this is the full result
/// of the squaring operation.
///
/// *Note*: doubles the scale of bigdecimal, which might lead to
/// accidental exponential-complexity if used in a loop.
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "1.1156024145937225657484".parse().unwrap();
/// assert_eq!(n.square(), "1.24456874744734405154288399835406316085210256".parse().unwrap());
///
/// let n: BigDecimal = "-9.238597585E+84".parse().unwrap();
/// assert_eq!(n.square(), "8.5351685337567832225E+169".parse().unwrap());
/// ```
pub fn square(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * &self.int_val,
scale: self.scale * 2,
}
}
}
/// Cube a decimal: *x³*
///
/// No rounding or truncating of digits; this is the full result
/// of the cubing operation.
///
/// *Note*: triples the scale of bigdecimal, which might lead to
/// accidental exponential-complexity if used in a loop.
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "1.1156024145937225657484".parse().unwrap();
/// assert_eq!(n.cube(), "1.388443899780141911774491376394890472130000455312878627147979955904".parse().unwrap());
///
/// let n: BigDecimal = "-9.238597585E+84".parse().unwrap();
/// assert_eq!(n.cube(), "-7.88529874035334084567570176625E+254".parse().unwrap());
/// ```
pub fn cube(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * &self.int_val * &self.int_val,
scale: self.scale * 3,
}
}
}
/// Take the square root of the number
///
/// Uses default-precision, set from build time environment variable
//// `RUST_BIGDECIMAL_DEFAULT_PRECISION` (defaults to 100)
///
/// If the value is < 0, None is returned
///
/// ```
/// # use bigdecimal::BigDecimal;
/// let n: BigDecimal = "1.1156024145937225657484".parse().unwrap();
/// assert_eq!(n.sqrt().unwrap(), "1.056220817156016181190291268045893004363809142172289919023269377496528394924695970851558013658193913".parse().unwrap());
///
/// let n: BigDecimal = "-9.238597585E+84".parse().unwrap();
/// assert_eq!(n.sqrt(), None);
/// ```
#[inline]
pub fn sqrt(&self) -> Option<BigDecimal> {
if self.is_zero() || self.is_one() {
return Some(self.clone());
}
if self.is_negative() {
return None;
}
// make guess
let guess = {
let magic_guess_scale = 1.1951678538495576_f64;
let initial_guess = (self.int_val.bits() as f64 - self.scale as f64 * LOG2_10) / 2.0;
let res = magic_guess_scale * exp2(initial_guess);
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale = (self.int_val.bits() as f64 / -LOG2_10 + self.scale as f64).round() as i64;
BigDecimal::new(BigInt::from(1), scale / 2)
}
};
// // wikipedia example - use for testing the algorithm
// if self == &BigDecimal::from_str("125348").unwrap() {
// running_result = BigDecimal::from(600)
// }
// TODO: Use context variable to set precision
let max_precision = DEFAULT_PRECISION;
let next_iteration = move |r: BigDecimal| {
// division needs to be precise to (at least) one extra digit
let tmp = impl_division(
self.int_val.clone(),
&r.int_val,
self.scale - r.scale,
max_precision + 1,
);
// half will increase precision on each iteration
(tmp + r).half()
};
// calculate first iteration
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
// calculate next iteration
running_result = next_iteration(running_result);
// 'result' has clipped precision, 'running_result' has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return Some(result);
}
/// Take the cube root of the number
///
#[inline]
pub fn cbrt(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
return self.clone();
}
if self.is_negative() {
return -self.abs().cbrt();
}
// make guess
let guess = {
let magic_guess_scale = 1.124960491619939_f64;
let initial_guess = (self.int_val.bits() as f64 - self.scale as f64 * LOG2_10) / 3.0;
let res = magic_guess_scale * exp2(initial_guess);
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale = (self.int_val.bits() as f64 / LOG2_10 - self.scale as f64).round() as i64;
BigDecimal::new(BigInt::from(1), -scale / 3)
}
};
// TODO: Use context variable to set precision
let max_precision = DEFAULT_PRECISION;
let three = BigDecimal::from(3);
let next_iteration = move |r: BigDecimal| {
let sqrd = r.square();
let tmp = impl_division(
self.int_val.clone(),
&sqrd.int_val,
self.scale - sqrd.scale,
max_precision + 1,
);
let tmp = tmp + r.double();
impl_division(tmp.int_val, &three.int_val, tmp.scale - three.scale, max_precision + 1)
};
// result initial
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
running_result = next_iteration(running_result);
// result has clipped precision, running_result has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return result;
}
/// Compute the reciprical of the number: x<sup>-1</sup>
#[inline]
pub fn inverse(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
return self.clone();
}
if self.is_negative() {
return self.abs().inverse().neg();
}
let guess = {
let bits = self.int_val.bits() as f64;
let scale = self.scale as f64;
let magic_factor = 0.721507597259061_f64;
let initial_guess = scale * LOG2_10 - bits;
let res = magic_factor * exp2(initial_guess);
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale = (bits / LOG2_10 + scale).round() as i64;
BigDecimal::new(BigInt::from(1), -scale)
}
};
let max_precision = DEFAULT_PRECISION;
let next_iteration = move |r: BigDecimal| {
let two = BigDecimal::from(2);
let tmp = two - self * &r;
r * tmp
};
// calculate first iteration
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
// calculate next iteration
running_result = next_iteration(running_result).with_prec(max_precision);
// 'result' has clipped precision, 'running_result' has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return result;
}
/// Return number rounded to round_digits precision after the decimal point
pub fn round(&self, round_digits: i64) -> BigDecimal {
// we have fewer digits than we need, no rounding
if round_digits >= self.scale {
return self.with_scale(round_digits);
}
let (sign, double_digits) = self.int_val.to_radix_le(100);
let last_is_double_digit = *double_digits.last().unwrap() >= 10;
let digit_count = (double_digits.len() - 1) * 2 + 1 + last_is_double_digit as usize;
// relevant digit positions: each "pos" is position of 10^{pos}
let least_significant_pos = -self.scale;
let most_sig_digit_pos = digit_count as i64 + least_significant_pos - 1;
let rounding_pos = -round_digits;
// digits are too small, round to zero
if rounding_pos > most_sig_digit_pos + 1 {
return BigDecimal::zero();
}
// highest digit is next to rounding point
if rounding_pos == most_sig_digit_pos + 1 {
let (&last_double_digit, remaining) = double_digits.split_last().unwrap();
let mut trailing_zeros = remaining.iter().all(|&d| d == 0);
let last_digit = if last_is_double_digit {
let (high, low) = num_integer::div_rem(last_double_digit, 10);
trailing_zeros &= low == 0;
high
} else {
last_double_digit
};
if last_digit > 5 || (last_digit == 5 && !trailing_zeros) {
return BigDecimal::new(BigInt::one(), round_digits);
}
return BigDecimal::zero();
}
let double_digits_to_remove = self.scale - round_digits;
debug_assert!(double_digits_to_remove > 0);
let (rounding_idx, rounding_offset) = num_integer::div_rem(double_digits_to_remove as usize, 2);
debug_assert!(rounding_idx <= double_digits.len());
let (low_digits, high_digits) = double_digits.as_slice().split_at(rounding_idx);
debug_assert!(high_digits.len() > 0);
let mut unrounded_uint = num_bigint::BigUint::from_radix_le(high_digits, 100).unwrap();
let rounded_uint;
if rounding_offset == 0 {
let high_digit = high_digits[0] % 10;
let (&top, rest) = low_digits.split_last().unwrap_or((&0u8, &[]));
let (low_digit, lower_digit) = num_integer::div_rem(top, 10);
let trailing_zeros = lower_digit == 0 && rest.iter().all(|&d| d == 0);
let rounding = if low_digit < 5 {
0
} else if low_digit > 5 || !trailing_zeros {
1
} else {
high_digit % 2
};
rounded_uint = unrounded_uint + rounding;
} else {
let (high_digit, low_digit) = num_integer::div_rem(high_digits[0], 10);
let trailing_zeros = low_digits.iter().all(|&d| d == 0);
let rounding = if low_digit < 5 {
0
} else if low_digit > 5 || !trailing_zeros {
1
} else {
high_digit % 2
};
// shift unrounded_uint down,
unrounded_uint /= num_bigint::BigUint::from_u8(10).unwrap();
rounded_uint = unrounded_uint + rounding;
}
let rounded_int = num_bigint::BigInt::from_biguint(sign, rounded_uint);
BigDecimal::new(rounded_int, round_digits)
}
/// Return true if this number has zero fractional part (is equal
/// to an integer)
///
#[inline]
pub fn is_integer(&self) -> bool {
if self.scale <= 0 {
true
} else {
(self.int_val.clone() % ten_to_the(self.scale as u64)).is_zero()
}
}
/// Evaluate the natural-exponential function e<sup>x</sup>
///
#[inline]
pub fn exp(&self) -> BigDecimal {
if self.is_zero() {
return BigDecimal::one();
}
let target_precision = DEFAULT_PRECISION;
let precision = self.digits();
let mut term = self.clone();
let mut result = self.clone() + BigDecimal::one();
let mut prev_result = result.clone();
let mut factorial = BigInt::one();
for n in 2.. {
term *= self;
factorial *= n;
// ∑ term=x^n/n!
result += impl_division(term.int_val.clone(), &factorial, term.scale, 117 + precision);
let trimmed_result = result.with_prec(target_precision + 5);
if prev_result == trimmed_result {
return trimmed_result.with_prec(target_precision);
}
prev_result = trimmed_result;
}
unreachable!("Loop did not converge")
}
#[must_use]
pub fn normalized(&self) -> BigDecimal {
if self == &BigDecimal::zero() {
return BigDecimal::zero();
}
let (sign, mut digits) = self.int_val.to_radix_be(10);
let trailing_count = digits.iter().rev().take_while(|i| **i == 0).count();
let trunc_to = digits.len() - trailing_count;
digits.truncate(trunc_to);
let int_val = BigInt::from_radix_be(sign, &digits, 10).unwrap();
let scale = self.scale - trailing_count as i64;
BigDecimal::new(int_val, scale)
}
}
#[derive(Debug, PartialEq)]
pub enum ParseBigDecimalError {
ParseDecimal(ParseFloatError),
ParseInt(ParseIntError),
ParseBigInt(ParseBigIntError),
Empty,
Other(String),
}
impl fmt::Display for ParseBigDecimalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use ParseBigDecimalError::*;
match *self {
ParseDecimal(ref e) => e.fmt(f),
ParseInt(ref e) => e.fmt(f),
ParseBigInt(ref e) => e.fmt(f),
Empty => "Failed to parse empty string".fmt(f),
Other(ref reason) => reason[..].fmt(f),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParseBigDecimalError {
fn description(&self) -> &str {
"failed to parse bigint/biguint"
}
}
impl From<ParseFloatError> for ParseBigDecimalError {
fn from(err: ParseFloatError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseDecimal(err)
}
}
impl From<ParseIntError> for ParseBigDecimalError {
fn from(err: ParseIntError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseInt(err)
}
}
impl From<ParseBigIntError> for ParseBigDecimalError {
fn from(err: ParseBigIntError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseBigInt(err)
}
}
impl FromStr for BigDecimal {
type Err = ParseBigDecimalError;
#[inline]
fn from_str(s: &str) -> Result<BigDecimal, ParseBigDecimalError> {
BigDecimal::from_str_radix(s, 10)
}
}
#[allow(deprecated)] // trim_right_match -> trim_end_match
impl Hash for BigDecimal {
fn hash<H: Hasher>(&self, state: &mut H) {