0.2

balancedternary.tgz (0.2, unix)

Overview

Abstract

BTernary is an implementation of the base-3 Balanced Ternary number system. BTernary provides a class which acts as most Integer numbers, and provides mechanisms for performing arithmetic and converting to and from decimal.

Introduction

The balanced ternary numbering system has several advantages, most of which are not realizeable here. In particular, theoretically, the most efficient numbering system (mathematically) is the numbering system where if r is the radix and w is the width in digits, r*w is minimized while holding r**w constant. It turns out that base-e (~2.718) is the most efficient, with base-3 being the best possible integer. Most of the benefits would come from a computer that had ternary bits, but none exist at the moment. There are some benefits that derive from not just the computational efficiency.

A balanced ternary system doesn't use 0,1,2 to count, but -1,0,1 instead. I'm not going to go into the details of why this is a nice system; read this American Scientist article for more details. Some interesting items about balanced ternary is that there is no sign bit: if the MSB is bar-1, the whole number is negative. Negating the number is done by inverting all of the bits. Numbers are not as straightforward as non-balanced systems, but don't require any more mathematical operations and are curiously, aesthetically, pleasing.

Bar-one is a 1 with a bar over the top. Since bar-one isn't a common character, BTernary uses 'T', which is pretty close. Bar-one is shorthand for -1. Therefore, 1 = 1, 0 = 0, T = -1. Balanced ternary systems use the same algorithm as other bases, with the addition of the sign. Therefore, 11 is 1*3**1 + 1*3**0, or 4. 110 is 1*3**2 + 1*3**1 + 0*3**0, or 12. 1T is 1*3**1 + -1*3**0, or 2. It is pretty easy once you get used to it.

Example b-ternary numbers
1TT = 9 - 3 - 1 = 5
1T1 = 9 - 3 + 1 = 7
1000 = 27
1T00 = 27 - 9 = 18
1T1T = 27 - 9 + 3 - 1 = 20

I discoverd a few things about B-Ternarys during this implementation. Most, if not all, were already known by other people or myself, and some are similar to rules that apply in binary numbering, and I'd forgotten them. In any case, that didn't stop me from being excited when I discovered them again.

This class has most of the same operators as Integer, is a Comparable, and can be used in a Range.

All of the algorithms herein are of my own devising, and are nobody's fault but my own. I learned almost everything I know pertaining specifically to balanced ternary systems from the aforementioned URL.

Features

Operation

Usage

BTernary comes with a full test suite in the file test.rb. Refer to this file for examples of using the BTernary class. The file to include is "ternary.rb"; the class name is BTernary.

Status

To Do

Credits

As mentioned before, I got interested in balanced ternary systems after reading the American Scientist article, which first came to my attention via Slashdot.