Biased Ternary vs. Balanced Ternary
The Ternary Manifesto by Douglas W. Jones is an excellent source of information on the topic of (balanced) ternary representation. The author notes that
balanced ternary encoding is exactly equivalent to a biased encoding
Biased encoding is a way to encode signed numbers in (bounded) unsigned numbers using an offset b. To read a biased number, read it as usual, then subtract b to get the represented value.
Douglas W. Jones describes the connection between ternary biased and balanced numbers as follows, giving an example with two ternary digits (= trits).
Decimal Biased Balanced
4 22 ++
3 21 +0
2 20 +-
1 12 0+
0 11 00
-1 10 0-
-2 02 -+
-3 01 -0
-4 00 --
[...]
the natural bias b for an n-trit ternary number is all ones:
b = ⌊3n / 2⌋ = (3n-1) / 2
[...]
To convert biased numbers to balanced numbers, subtract 1 from each digit, so 2 becomes +1
(represented as +
), 1 becomes 0
(represented as 0
), and 0 becomes –1
(represented as -
).
[...]
This is merely a change of the symbols associated with the digits, a matter of how the digits are printed on the page, not a matter of how the digits are represented inside some mechanism. The difference between biased and balanced representations can be considered to be entirely cosmetic
Converting Integers to Balanced Ternary
To convert an integer i to balanced ternary
- Compute n, the number of digits in i's balanced ternary representation.
By solving |i| ≤ (3n-1) / 2 for n we know that n = ⌈log3(2|x|+1)⌉.
- Compute the bias b = (3n-1) / 2.
- Then convert i+b to a ternary string with n digits (leading
0
s are important!),
- and replace the characters
012
by -0+
.
Example implementation in Java's jshell:
import static java.lang.Math.*;
String balTer(int i) {
// n=…+1 and ….substring(1) ensure leading zeroes
int n = max(1, (int) ceil(log(2 * abs(i) + 1) / log(3))) + 1;
int b = ((int) pow(3, n) - 1) / 2;
return Integer.toString(i + b, 3).substring(1)
.replace('0', '-').replace('1', '0').replace('2', '+');
}
balTer(15) // returns "+--0"
+
-
and0
. Wikipedia uses1
T
and0
, respectively. And what exactly does Wikipedia say to do with the2
s? – Jarl