1.19 Ratio

Ratios are made with a couple of large integers : the numerator which can be any number, and the denominator which has to be positive. They represent fractions of integral numbers. They are written with a slash and no space.

ikc3> 1/2 + 2/3
7/6
ikc3> 1/2 * 2/3
1/3
ikc3> 1/2 / 2/3
3/4
ikc3> 1/2 - 2/3
-1/6

Division by zero reports an error and evaluates to Void. This also applies to mixed division between a Ratio and an Integer or fixed-width number.

Mixed arithmetic between a Ratio and a finite float returns a Ratio. The float is converted to its exact binary value, including its fractional part: (F64) 0.5 + 1/2 returns 1/1, and 1/2 / (F64) 1.25 returns 2/5. Float-to-Ratio casts use the same conversion. A decimal float such as (F64) 0.1 is represented by its stored binary value, 3602879701896397/36028797018963968, rather than 1/10. Both floating zeros become 0/1. NaN and infinities have no Ratio representation; conversion or mixed arithmetic with them reports an error and evaluates to Void.

Exponentiation requires an explicit number of significant precision bits:

ikc3> require Ratio
Ratio
ikc3> Ratio.pow(4/9, 1/2, (Uw) 64)
2/3
ikc3> Ratio.pow(4/9, -1/2, (Uw) 64)
3/2

Ratio.pow(base, exponent, precision_bits) returns a Ratio. Exact rational results are returned exactly. For an irrational real result y, the returned rational approximation r satisfies abs(r - y) <= abs(y) / 2^precision_bits. The precision must be a positive Uw; there is no default. Numerators and denominators remain arbitrary-precision Integers, including the components of the exponent.

For a negative base, the exponent is simplified first: an odd denominator allows the real root, while an even denominator gives an error. Zero with a negative exponent also gives an error. A zero exponent returns 1/1. The binary ** operator does not choose a precision for Ratio powers; use the explicit Ratio.pow call.

Approximation uses the logarithm and exponential series with argument scaling and outward rational bounds. All arithmetic stays in Integers and Ratios; the requested precision is verified against the resulting bounds. See NIST's logarithm series and exponential series.


Top : KC3 documentation

Previous : 1.18 Quote

Next : 1.20 Str