Table of Contents#### Download Safari Books Online apps: Apple iOS | Android | BlackBerry

### 4.2. Trying to be rational

#### 4.2.1. Why be rational?

Entire Site

Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Clojure provides a data type representing a rational number, and all of its core mathematical functions operate with rational numbers. Clojure’s rationals allow for arbitrarily large numerators and denominators. We won’t go into depth about the limitations of floating-point operations, but the problem can be summarized simply. Given a finite representation of an infinitely large set, a determination must be made which finite subset is represented. In the case of standard floating-point numbers as representations of real numbers, the distribution of represented numbers is logarithmic (Kuki 1973) and not one-for-one. What does this mean in practice? It means that requiring more accuracy in your floating-point operations increases the probability that the corresponding representation won’t be available. In these circumstances, you’ll have to settle for approximations. But Clojure’s rational number type provides a way to retain perfect accuracy when needed.

Of course, Clojure provides a decimal type that’s boundless relative to your computer memory, so why wouldn’t you just use those? In short, you can, but decimal operations can be easily corrupted, especially when working with existing Java libraries (Kahan 1998) taking and returning primitive types. Additionally, in the case of Java, its underlying `BigDecimal` class is finite in that it uses a 32-bit integer to represent the number of digits to the right of the decimal place. This can represent an extremely large range of values perfectly, but it’s still subject to error: