Fetching contributors…
Cannot retrieve contributors at this time
191 lines (127 sloc) 6.54 KB

!mpq data type

The !mpq data type can store rational numbers whose denominator and numerator have arbitrary size.

Rational numbers are converted in canonical form on input (meaning that the denominator and the numerator have no common factors) and all the operators will return a number in canonical form.

PostgreSQL integer types (!int16, !int32, !int64), !numeric and mpz can be converted to !mpq without loss of precision and without surprise. Floating point types (!float4, !float8) are converted without loss as well... but with some surprise, as many fractions with finite decimal expansion have no finite expansion in binary.

=# select 10.1::numeric::mpq as "numeric",
-#        10.1::float4::mpq as "single",
-#        10.1::float8::mpq as "double";
 numeric |     single     |              double
 101/10  | 5295309/524288 | 5685794529555251/562949953421312

!mpq values can be converted to integer types (both PostgreSQL's and !mpz): the result will be truncated. Conversion to !float4 and !float8 will round the values to the precision allowed by the types (in case of overflow the value will be Infinity). Conversion to !numeric will perform a rounding to the precision set for the target type.

=# select mpq('4/3')::integer as "integer",
-#        mpq('4/3')::float4 as "single",
-#        mpq('4/3')::decimal(10,3) as "decimal";
 integer | single  | decimal
       1 | 1.33333 |   1.333

!mpq values can be compared using the regular PostgreSQL comparison operators. Indexes on !mpq columns can be created using the btree or the hash method.

!mpq textual input/output

!mpq conversions

Arithmetic Operators and Functions

All the arithmetic operators and functions return their their output in canonical form.

Arithmetic operators
Operator Description Example Return
!- Unary minus !- '4/3'::mpq -4/3
!+ Unary plus !+ '4/3'::mpq 4/3
!+ Addition !'2/3'::mpq + '5/6'::mpq 3/2
!- Subtraction !'1/3'::mpq - '5/6'::mpq -1/2
!* Multiplication !'2/3'::mpq * '5/6'::mpq 5/9
!/ Division !'2/3'::mpq / '5/6'::mpq 4/5
!<< Multiplication by 2^n !'2/3'::mpq << 3 16/3
!>> Division by 2^n !'2/3'::mpq >> 3 1/12

Aggregation functions