Skip to main content

Crate ternaria_arith

Crate ternaria_arith 

Source
Expand description

Balanced ternary arithmetic.

Digits are -1, 0 and +1 (a Trit). A value is the sum of d_k * 3^k over its digits. One trit carries log2(3), about 1.585 bits.

Properties relied on elsewhere in the platform:

  • Negation flips every digit and requires no carry. There is no two’s complement representation and no signed/unsigned distinction.
  • The range is symmetric: n trits cover -(3^n-1)/2 to (3^n-1)/2. -x never overflows and Word::abs is total.
  • Truncation gives the correctly rounded result. Discarded digits are worth at most half a unit in the last place, and exact ties cannot occur.
  • Comparison has three outcomes and returns one trit. See Word::cmp3.

§Example

use ternaria_arith::{Trit, Word};

let a = Word::from_value(42);
let b = Word::from_value(-17);

assert_eq!(a.checked_add(b).unwrap().value(), 25);

// Negation cannot overflow.
assert_eq!((-a).value(), -42);
assert_eq!(Word::MIN.neg(), Word::MAX);

// Comparison returns one trit.
assert_eq!(b.cmp3(a), Trit::Neg);

// Balanced ternary notation: T is -1.
assert_eq!(a.to_string(), "1TTT0");
assert_eq!("1TTT0".parse::<Word>().unwrap(), a);

// A 27-trit product is exactly 54 trits, so this cannot overflow.
let exact = Word::MAX.widening_mul(Word::MAX);
assert_eq!(exact.to_i128(), 3_812_798_742_493i128.pow(2));

Structs§

DoubleWord
A double word, 54 balanced trits.
NatError
Error from decoding a BCT-packed value.
Tryte
A tryte, the addressable unit, 9 balanced trits.
Word
A word, 27 balanced trits.

Enums§

ParseTritsError
Error from parsing a balanced ternary literal.
Trit
A balanced ternary digit: -1, 0, or +1 (D-01).