Rational:
Filter:
(extension) Math

Rational
ExtensionExtension

Rational number

Description

A rational number. Alternative syntax: x %/ y

NOTE:

What is exact, and what is not

An operation with an exact rational answer gives one. floor, ceil, frac, trunc, round, roundUp, mod, wrap and fold are closed over the rationals, and each returns a Rational.

Everything else in the Number vocabulary is answered from asFloat, because there is no rational answer to give — a rational has no rational square root. respondsTo agrees with this, so a caller may ask before sending.

Refusals

A denominator of zero, a division by zero and the reciprocal of zero throw.

Class Methods

.new

Rational also accepts Floats and Strings in its new instantiation method. This class will always reduce a rational expression to its lowest terms (e.g. 3 %/ 2 instead of 6 %/ 4).

Instance Methods

%/

Alternative syntax for Rational(x,y)

+

Addition

-

Subtraction

*

Multiplication

/

Division

.abs

Absolute value.

.asFloat

As Float

.pow

.reciprocal

Reciprocal

.squared

Power of two

.isZero

Whether the numerator is zero, whatever the denominator.

.floor

.ceil

The nearest integer below and above, as a Rational.

.frac

The part above the floor, so never negative.

.trunc

.round

.roundUp

Quantize down, to nearest, and up. Like sclang's, these quantize toward -inf rather than toward zero, so (-7 %/ 2).trunc is -4 %/ 1.

.mod

Remainder, taking the sign of the divisor as sclang's does.

.wrap

.fold

Map into a range, wrapping or reflecting. These follow the Float definitions, where hi is outside the range —

NOTE: Integer:wrap and Float:wrap are different operations in sclang. 5.wrap(0,3) is 1 and 5.0.wrap(0,3) is 2.0. A Rational is a continuous quantity, so it follows the Float one.

.do

.reverseDo

Iterate as a number, counting exactly as the equivalent Float does.

Examples

Basic operations

Comparisons

Sorting

Continued fractions

Recursive function to calculate finite continued fractions:

Stern-Brocot numbers

In number theory, the Stern–Brocot tree is an infinite complete binary tree in which the vertices correspond one-for-one to the positive rational numbers, whose values are ordered from the left to the right as in a search tree.

Conversion between Rational and Float

Conversion between Float and Rational can have different degrees of precision:

Sound Example