|
| 1 | +[Algebraic Numbers](https://en.wikipedia.org/wiki/Algebraic_number) Library |
| 2 | + |
| 3 | +Use when you need exact arithmetic, speed is not critical, and rational numbers aren't good enough. |
| 4 | + |
| 5 | +Example: |
| 6 | +```rust |
| 7 | +use algebraics::prelude::*; |
| 8 | +use algebraics::RealAlgebraicNumber as Number; |
| 9 | + |
| 10 | +let two = Number::from(2); |
| 11 | + |
| 12 | +// 2 is a rational number |
| 13 | +assert!(two.is_rational()); |
| 14 | + |
| 15 | +// 1/2 is the reciprocal of 2 |
| 16 | +let one_half = two.recip(); |
| 17 | + |
| 18 | +// 1/2 is also a rational number |
| 19 | +assert!(one_half.is_rational()); |
| 20 | + |
| 21 | +// 2^(1/4) |
| 22 | +let root = (&two).pow((1, 4)); |
| 23 | + |
| 24 | +// we can use all the standard comparison operators |
| 25 | +assert!(root != Number::from(3)); |
| 26 | +assert!(root < Number::from(2)); |
| 27 | +assert!(root > Number::from(1)); |
| 28 | + |
| 29 | +// we can use all of add, subtract, multiply, divide, and remainder |
| 30 | +let sum = &root + &root; |
| 31 | +let difference = &root - Number::from(47); |
| 32 | +let product = &root * &one_half; |
| 33 | +let quotient = &one_half / &root; |
| 34 | +let remainder = &root % &one_half; |
| 35 | + |
| 36 | +// root is not a rational number |
| 37 | +assert!(!root.is_rational()); |
| 38 | + |
| 39 | +// the calculations are always exact |
| 40 | +assert_eq!((&root).pow(4), two); |
| 41 | + |
| 42 | +// lets compute 30 decimal places of root |
| 43 | +let scale = Number::from(10).pow(30); |
| 44 | +let scaled = &root * scale; |
| 45 | +let digits = scaled.into_integer_trunc(); |
| 46 | +assert_eq!( |
| 47 | + digits.to_string(), |
| 48 | + 1_18920_71150_02721_06671_74999_70560u128.to_string() |
| 49 | +); |
| 50 | + |
| 51 | +// get the minimal polynomial |
| 52 | +let other_number = root + two.pow((1, 2)); |
| 53 | +assert_eq!( |
| 54 | + &other_number.minimal_polynomial().to_string(), |
| 55 | + "2 + -8*X + -4*X^2 + 0*X^3 + 1*X^4" |
| 56 | +); |
| 57 | +``` |
0 commit comments