webgriffe / rational
A data type used to represent rational numbers
Requires
- php: ~8.2
- ext-gmp: *
- ext-intl: *
- webmozart/assert: ^2.0
Requires (Dev)
- phpunit/phpunit: ^10.0 || ^11.0 || ^12.0 || ^13.0
README
Rational - A simple rational number implementation
Features
This library implements a numeric data type that represents a rational number, that is a number that can be exactly represented as the division of two integer numbers. This includes periodic numbers (such as 0.333333..., which can be exactly represented as ⅓) and those numbers that cannot be represented exactly by a floating point type (such as 0.1, which is a periodic number in binary representation, but which can be represented by the fraction ⅒).
In order to reduce the possibility of large values triggering overflow issues, an integer "whole" part is added to the fraction. This means that values are stored as mixed numbers of the form a + b/c, where a, b and c are all integers.
Calculations are performed using the GMP extension for arbitrary precision integers. This ensures that there is no possibility of overflow errors being generated by intermediate results before they are simplified and normalized.
At the end of each operation, after all simplification and normalization steps, if the final results still do not fit into PHP's standard integer type, then an overflow exception is generated.
This library is very similar to https://github.com/markrogoyski/math-php/blob/master/src/Number/Rational.php, with the main difference being that this implementation uses the GMP extension internally to ensure that no overflow issues can arise with the intermediate computation results. In addition, this implementation offers floor(), ceil() and round() methods that allows one to round a Rational to a value that can be represented with the specified maximum number of decimal digits. These can be useful when dealing with things such as money, where payment providers cannot handle payments of like 4⅓€
Setup
Install the library using Composer:
$ php composer.phar require webgriffe/rational
Composer will install the library in your vendor folder. If you don't already use Composer in your project, you may need to explicitly include its autoload file in order to allow PHP to find the library class(es):
require_once __DIR__ . '/vendor/autoload.php';
Minimum Requirements
- PHP 8.2 or later, with the GMP extension installed
Usage
Since floating point number are inherently inaccurate, it was deliberately decided NOT to provide a way to initialize a rational number from a float. Likewise, no method is provided to convert a rational to a float for the same reason.
Creating rational numbers is possible starting from integers or from the various components of the rational number:
use Webgriffe\Rational; //Creates a Rational with the value zero $r0 = Rational::zero(); //Creates a Rational with the value one $r1 = Rational::one(); //Creates a Rational with an integer value $r2 = Rational::fromWhole(-2); //Creates a Rational that stores exactly ⅔ (two thirds), roughly 0.666666... $r3 = Rational::fromFraction(2, 3); //Creates a Rational that stores exactly 4 + ⅑ (one ninth), roughly 7.111111... $r4 = Rational::fromWholeAndFraction(4, 1, 9); //Adds $r1 and $r2 so that $r5 equals -1 $r5 = $r1->add($r2); //Adds $r3 to $r5: -1 + ⅔ = -⅓ $r6 = $r5->add($r3); //Subtracts $r6 from $r2: -2 - (-⅓) = -2 + ⅓ = -1 - ⅔ $r7 = $r2->sub($r6); //Multiply $r7 by $r4: (-1 - ⅔) * (4 + ⅑) //= -4 - 1/9 - 8/3 - 2/27 //= -4 - 3/27 - 72/27 - 2/27 //= -4 - 77/27 //= -4 - 2 - 23/27 //= -6 - 23/27 $r8 = $r7->mul($r4); //Divide $r8 by $r3: (-6 - 23/27) / (2/3) //= (-6 - 23/27) * (3/2) //= -9 - 23/18 //= -9 - 1 - 5/18 //= -10 - 5/18 $r9 = $r8->div($r3); //Compute the reciprocal of $r9: 1/(-10 - 5/18) //= 1/((-180 - 5)/18) //= 1/(-185/18) //= 18/-185 //= -18/185 $r10 = $r9->recip(); //$r11 = $r10 + $r1: -18/185 + 1 //= -18/185 + 185/185 //= 167/185 $r11 = $r10->add($r1); //Prints 0.903 echo $r11->toDecimalString(3); //Round to a value that can be represented with at most 2 decimals, then print it forcing exactly 2 decimals to print 0.90. //Useful when dealing with prices echo $r11->round(2)->toDecimalString(2, 2); //$r12 = $r11 - $r10: 167/185 - (-18/185) //= 167/185 + 18/185 //= 185/185 //= 1 $r12 = $r11->sub($r10);
Usage in an application
Extension
It is possible to extend the Rational class to seamlessly use it in application-specific contexts.
For example, if one wants to use the Rational class to represent percentages, it is possible to define a Percentage class that extends Rational:
use Webgriffe\Rational; final class Percentage extends Rational { }
All methods are type-hinted in such a way that all results will be identified as having the type of the first operand of each operation. So, for example, if a Percentage object is added to another Percentage, the result will be of type Percentage as well.
Containment
Of course, it is also possible to encapsulate instances of Rational inside other classes:
use Webgriffe\Rational; class Money { public function __construct( private readonly Rational $value, private readonly string $currency, ) { } public function add(self $other): static { if ($other->currency !== $this->currency) { //Error } return new static($this->value->add($other->value), $this->currency); } public function mul(Rational $other): static { return new static($this->value->mul($other), $this->currency); } public function div(self $other): Rational { if ($other->currency !== $this->currency) { //Error } return $this->value->div($other->value); } ... }
This has the benefit that one can control precisely what operations are allowed and what are not. For example, for a class that represents amounts of money, the reciprocal operation may not make much sense. Likewise, multiplying an amount of money by another amount of money may not be sensible, one can multiply an amount of money by a pure number. Division may make sense, but its result would not be a money object, it would be a plain Rational object.
The drawback is that one has to manually redefine all the desired arithmetic operations to work on the contained Rational value.
Persistence
Many applications have a need to persist values to a database or some other storage system. To facilitate this, a trait is provided, RationalSerializerTrait. It provides methods to serialize and deserialize Rational objects into strings, which can then be easily stored in a database. The trait is designed to be used with Doctrine custom data types, but it can be adapted to other storage engines.
Errors
Overflow
At the end of every operation the library converts the intermediate GMP values back to integers. If these values are too large or too small to fit into an integer, a OverflowException is thrown. It is the user's responsibility to catch the exception and act accordingly.
Underflow
This error can happen if the numerator and/or denominator of the fraction part become too large to fit into regular PHP integers. In this case it is not possible to represent the result of the operation exactly, but one may decide to accept an approximation. Therefore, when an underflow is detected, the library reports the issue and provides the representable value that is closest to the exact result. The user of the library can then decide whether to use that value to continue with the calculation or to stop if no approximation is acceptable.
Internal working
The library stores all components of the rational number as PHP integers. This is to make it easier to store these values to databases and other media where storing arbitrary-length integers may be problematic. Intermediate values are handled through the PHP GMP library in order to avoid overflow issues until the final results are computed. So, for example, if one multiplies two large fractions, as long as the result after simplification can fit into standard PHP integers then no overflow will occur. If, however, the final result of a call to any Rational method cannot be represented via PHP integers, the library reports an overflow error.
Immediately after creation and after every operation, each value is normalized. The purpose of this is to reduce the magnitude of the values stored internally and to make it easier to compare rational numbers and to extract other useful information.
In the context of this library which stores values as a + b/c, a normalized value is one where c > 0, where a * b >= 0 (i.e. they do not disagree in sign, though one or both can be zero), where GCD(|b|, c) == 1 (i.e. the fraction b/c is simplified) and |a| < b (i.e. it is a proper fraction).
License
Webgriffe/Rational is licensed under the MIT License.