BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / push / vendor / brick / math / README.md

README.md

README.md 11.3 KiB Download Raw

Brick\Math

A PHP library to work with arbitrary precision numbers.

Build Status Coverage Status Latest Stable Version Total Downloads License

Installation

This library is installable via Composer:

composer require brick/math

Requirements

This library requires PHP 8.2 or later.

For PHP 8.1 compatibility, you can use version 0.13. For PHP 8.0, you can use version 0.11. For PHP 7.4, you can use version 0.10. For PHP 7.1, 7.2 & 7.3, you can use version 0.9. Note that PHP versions < 8.1 are EOL and not supported anymore. If you're still using one of these PHP versions, you should consider upgrading as soon as possible.

Although the library can work seamlessly on any PHP installation, it is highly recommended that you install the GMP or BCMath extension to speed up calculations. The fastest available calculator implementation will be automatically selected at runtime.

Project status & release process

While this library is still under development, it is well tested and considered stable enough to use in production environments.

The current releases are numbered 0.x.y. When a non-breaking change is introduced (adding new methods, optimizing existing code, etc.), y is incremented.

When a breaking change is introduced, a new 0.x version cycle is always started.

It is therefore safe to lock your project to a given release cycle, such as ^0.20.

If you need to upgrade to a newer release cycle, check the release history for a list of changes introduced by each further 0.x.0 version.

Package contents

This library provides the following public classes in the Brick\Math namespace:

  • BigNumber: base class for BigInteger, BigDecimal and BigRational
  • BigInteger: represents an arbitrary-precision integer number.
  • BigDecimal: represents an arbitrary-precision decimal number.
  • BigRational: represents an arbitrary-precision rational number (fraction), always reduced to lowest terms.
  • RoundingMode: enum representing all available rounding modes.

And exceptions in the Brick\Math\Exception namespace.

Overview

Instantiation

The constructors of the classes are not public, you must use a factory method to obtain an instance.

All classes provide an of() factory method that accepts any of the following types:

  • BigNumber instances
  • int numbers
  • string representations of integer, decimal and rational numbers

Example:

BigInteger::of(123546);
BigInteger::of('9999999999999999999999999999999999999999999');

BigDecimal::of('9.99999999999999999999999999999999999999999999');

BigRational::of('2/3');

Note that all of() methods accept all the representations above, as long as it can be safely converted to the current type:

BigInteger::of('1.00'); // 1
BigInteger::of('1.01'); // RoundingNecessaryException

BigDecimal::of('1/8'); // 0.125
BigDecimal::of('1/3'); // RoundingNecessaryException

BigRational::of('1.1'); // 11/10
BigRational::of('1.15'); // 23/20 (reduced to lowest terms)

> [!NOTE] > The of() factory method does not accept float values, because casting a float to string can be lossy. > To convert a float to a BigDecimal, use one of the dedicated methods: > > php > // Exact IEEE-754 representation — the value the float actually holds: > BigDecimal::fromFloatExact(0.1); // 0.1000000000000000055511151231257827021181583404541015625 > > // Shortest decimal that round-trips back to the same float: > BigDecimal::fromFloatShortest(0.1); // 0.1 >

Parsing untrusted input

of() places no hard limits on its input: a string with millions of digits is accepted as is, and a number in exponential notation is expanded to its full length, so a string as short as 1e1000000000 yields a number with a billion digits.

If your input comes from an untrusted source, such as an HTTP request, use parse() instead, which requires you to specify the allowed syntax and a maximum number of digits:

use Brick\Math\NumberSyntax;

BigDecimal::parse($input, allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20);

The $allowedSyntax parameter restricts the accepted notations. Plain integers such as 123 are always accepted, and each NumberSyntax case (DecimalPoint, Exponent, Fraction) allows one additional feature. The enum also provides constants for the most common combinations:

  • NumberSyntax::INTEGER — integers only: 123
  • NumberSyntax::DECIMAL — integers and decimal numbers: 123, 123.45; typical for monetary input
  • NumberSyntax::SCIENTIFIC — integers, decimal numbers and exponents: 123, 123.45, 1.5e-3; accepts every JSON number
  • NumberSyntax::RATIONAL — integers and fractions: 123, 22/7
  • NumberSyntax::ALL — the full syntax accepted by of(): 123, 123.45, 1.5e-3, 22/7

The $maxDigits parameter limits the number of digits, counted both as written in the input and in the resulting number, so that a value such as 1e1000000000 is rejected before it is ever expanded:

BigDecimal::parse('123.45', allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20); // 123.45
BigDecimal::parse('1.2e3', allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20); // NumberFormatException (exponent not allowed)
BigDecimal::parse('1e1000000000', allowedSyntax: NumberSyntax::SCIENTIFIC, maxDigits: 20); // NumberFormatException (too many digits)

Immutability & chaining

The BigInteger, BigDecimal and BigRational classes are immutable: their value never changes, so that they can be safely passed around. All methods that return a BigInteger, BigDecimal or BigRational return a new object, leaving the original object unaffected:

$ten = BigInteger::of(10);

echo $ten->plus(5); // 15
echo $ten->multipliedBy(3); // 30

The methods can be chained for better readability:

echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45

Parameter types

All methods that accept a number: plus(), minus(), multipliedBy(), etc. accept the same types as of(). For example, given the following number:

$integer = BigInteger::of(123);

The following lines are equivalent:

$integer->multipliedBy(123);
$integer->multipliedBy('123');
$integer->multipliedBy($integer);

Just like of(), other types of BigNumber are acceptable, as long as they can be safely converted to the current type:

echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.0')); // 4
echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.5')); // RoundingNecessaryException
echo BigDecimal::of(2.5)->multipliedBy(BigInteger::of(2)); // 5.0

These parameters are converted with of(), so the same rules apply: for untrusted strings, use parse() first, and pass the resulting number to the method.

Division & rounding

BigInteger

By default, dividing a BigInteger returns the exact result of the division, or throws an exception if the remainder of the division is not zero:

echo BigInteger::of(999)->dividedBy(3); // 333
echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException

You can pass an optional rounding mode to round the result, if necessary:

echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Down); // 333
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Up); // 334

If you're into quotients and remainders, there are methods for this, too:

echo BigInteger::of(1000)->quotient(3); // 333
echo BigInteger::of(1000)->remainder(3); // 1

You can even get both at the same time:

[$quotient, $remainder] = BigInteger::of(1000)->quotientAndRemainder(3);
BigDecimal

Dividing a BigDecimal always requires a scale to be specified. If the exact result of the division does not fit in the given scale, a rounding mode must be provided.

echo BigDecimal::of(1)->dividedBy('8', 3); // 0.125
echo BigDecimal::of(1)->dividedBy('8', 2); // RoundingNecessaryException
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfDown); // 0.12
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfUp); // 0.13

If you know that the division yields a finite number of decimals places, you can use dividedByExact(), which will automatically compute the required scale to fit the result, or throw an exception if the division yields an infinite repeating decimal:

echo BigDecimal::of(1)->dividedByExact(256); // 0.00390625
echo BigDecimal::of(1)->dividedByExact(11); // RoundingNecessaryException
BigRational

The result of the division of a BigRational can always be represented exactly:

echo BigRational::of('13/99')->dividedBy('7'); // 13/693
echo BigRational::of('13/99')->dividedBy('9/8'); // 104/891

Bitwise operations

BigInteger supports bitwise operations:

  • and()
  • or()
  • xor()
  • not()

and bit shifting:

  • shiftedLeft()
  • shiftedRight()

Exceptions

All exceptions thrown by this library implement the MathException interface. This means that you can safely catch all exceptions thrown by this library using a single catch clause:

use Brick\Math\BigDecimal;
use Brick\Math\Exception\MathException;

try {
    $number = BigInteger::of(1)->dividedBy(3);
} catch (MathException $e) {
    // ...
}

If you need more granular control over the exceptions thrown, you can catch the specific exception classes:

  • DivisionByZeroException
  • IntegerOverflowException
  • InvalidArgumentException
  • NegativeNumberException
  • NoInverseException
  • NumberFormatException
  • PlatformException
  • RandomSourceException
  • RoundingNecessaryException

Serialization

BigInteger, BigDecimal and BigRational can be safely serialized on a machine and unserialized on another, even if these machines do not share the same set of PHP extensions.

For example, serializing on a machine with GMP support and unserializing on a machine that does not have this extension installed will still work as expected.

PHPStan extension

A third-party PHPStan extension is available for this library. It provides more specific throw type narrowing for brick/math methods, so that PHPStan can infer the exact exception classes thrown. Note that this extension is not maintained by the author of brick/math.

Source
1## Brick\Math
2
3<img src="https://raw.githubusercontent.com/brick/brick/master/logo.png" alt="" align="left" height="64">
4
5A PHP library to work with arbitrary precision numbers.
6
7[![Build Status](https://github.com/brick/math/workflows/CI/badge.svg)](https://github.com/brick/math/actions)
8[![Coverage Status](https://codecov.io/github/brick/math/graph/badge.svg)](https://codecov.io/github/brick/math)
9[![Latest Stable Version](https://poser.pugx.org/brick/math/v/stable)](https://packagist.org/packages/brick/math)
10[![Total Downloads](https://poser.pugx.org/brick/math/downloads)](https://packagist.org/packages/brick/math)
11[![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)
12
13### Installation
14
15This library is installable via [Composer](https://getcomposer.org/):
16
17```bash
18composer require brick/math
19```
20
21### Requirements
22
23This library requires PHP 8.2 or later.
24
25For PHP 8.1 compatibility, you can use version `0.13`. For PHP 8.0, you can use version `0.11`. For PHP 7.4, you can use version `0.10`. For PHP 7.1, 7.2 & 7.3, you can use version `0.9`. Note that [PHP versions < 8.1 are EOL](http://php.net/supported-versions.php) and not supported anymore. If you're still using one of these PHP versions, you should consider upgrading as soon as possible.
26
27Although the library can work seamlessly on any PHP installation, it is highly recommended that you install the
28[GMP](http://php.net/manual/en/book.gmp.php) or [BCMath](http://php.net/manual/en/book.bc.php) extension
29to speed up calculations. The fastest available calculator implementation will be automatically selected at runtime.
30
31### Project status & release process
32
33While this library is still under development, it is well tested and considered stable enough to use in production
34environments.
35
36The current releases are numbered `0.x.y`. When a non-breaking change is introduced (adding new methods, optimizing
37existing code, etc.), `y` is incremented.
38
39**When a breaking change is introduced, a new `0.x` version cycle is always started.**
40
41It is therefore safe to lock your project to a given release cycle, such as `^0.20`.
42
43If you need to upgrade to a newer release cycle, check the [release history](https://github.com/brick/math/releases)
44for a list of changes introduced by each further `0.x.0` version.
45
46### Package contents
47
48This library provides the following public classes in the `Brick\Math` namespace:
49
50- [BigNumber](https://github.com/brick/math/blob/0.20.0/src/BigNumber.php): base class for `BigInteger`, `BigDecimal` and `BigRational`
51- [BigInteger](https://github.com/brick/math/blob/0.20.0/src/BigInteger.php): represents an arbitrary-precision integer number.
52- [BigDecimal](https://github.com/brick/math/blob/0.20.0/src/BigDecimal.php): represents an arbitrary-precision decimal number.
53- [BigRational](https://github.com/brick/math/blob/0.20.0/src/BigRational.php): represents an arbitrary-precision rational number (fraction), always reduced to lowest terms.
54- [RoundingMode](https://github.com/brick/math/blob/0.20.0/src/RoundingMode.php): enum representing all available rounding modes.
55
56And [exceptions](#exceptions) in the `Brick\Math\Exception` namespace.
57
58### Overview
59
60#### Instantiation
61
62The constructors of the classes are not public, you must use a factory method to obtain an instance.
63
64All classes provide an `of()` factory method that accepts any of the following types:
65
66- `BigNumber` instances
67- `int` numbers
68- `string` representations of integer, decimal and rational numbers
69
70Example:
71
72```php
73BigInteger::of(123546);
74BigInteger::of('9999999999999999999999999999999999999999999');
75
76BigDecimal::of('9.99999999999999999999999999999999999999999999');
77
78BigRational::of('2/3');
79```
80
81Note that all `of()` methods accept all the representations above, *as long as it can be safely converted to
82the current type*:
83
84```php
85BigInteger::of('1.00'); // 1
86BigInteger::of('1.01'); // RoundingNecessaryException
87
88BigDecimal::of('1/8'); // 0.125
89BigDecimal::of('1/3'); // RoundingNecessaryException
90
91BigRational::of('1.1'); // 11/10
92BigRational::of('1.15'); // 23/20 (reduced to lowest terms)
93```
94
95> [!NOTE]
96> The `of()` factory method does not accept `float` values, because casting a float to string can be lossy.
97> To convert a float to a `BigDecimal`, use one of the dedicated methods:
98>
99> ```php
100> // Exact IEEE-754 representation — the value the float actually holds:
101> BigDecimal::fromFloatExact(0.1); // 0.1000000000000000055511151231257827021181583404541015625
102>
103> // Shortest decimal that round-trips back to the same float:
104> BigDecimal::fromFloatShortest(0.1); // 0.1
105> ```
106
107#### Parsing untrusted input
108
109`of()` places no hard limits on its input: a string with millions of digits is accepted as is, and a number in
110exponential notation is expanded to its full length, so a string as short as `1e1000000000` yields a number with
111a billion digits.
112
113If your input comes from an untrusted source, such as an HTTP request, use `parse()` instead, which requires you
114to specify the allowed syntax and a maximum number of digits:
115
116```php
117use Brick\Math\NumberSyntax;
118
119BigDecimal::parse($input, allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20);
120```
121
122The `$allowedSyntax` parameter restricts the accepted notations. Plain integers such as `123` are always accepted,
123and each `NumberSyntax` case (`DecimalPoint`, `Exponent`, `Fraction`) allows one additional feature. The enum also
124provides constants for the most common combinations:
125
126- `NumberSyntax::INTEGER` — integers only: `123`
127- `NumberSyntax::DECIMAL` — integers and decimal numbers: `123`, `123.45`; typical for monetary input
128- `NumberSyntax::SCIENTIFIC` — integers, decimal numbers and exponents: `123`, `123.45`, `1.5e-3`; accepts every JSON number
129- `NumberSyntax::RATIONAL` — integers and fractions: `123`, `22/7`
130- `NumberSyntax::ALL` — the full syntax accepted by `of()`: `123`, `123.45`, `1.5e-3`, `22/7`
131
132The `$maxDigits` parameter limits the number of digits, counted both as written in the input and in the resulting number,
133so that a value such as `1e1000000000` is rejected before it is ever expanded:
134
135```php
136BigDecimal::parse('123.45', allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20); // 123.45
137BigDecimal::parse('1.2e3', allowedSyntax: NumberSyntax::DECIMAL, maxDigits: 20); // NumberFormatException (exponent not allowed)
138BigDecimal::parse('1e1000000000', allowedSyntax: NumberSyntax::SCIENTIFIC, maxDigits: 20); // NumberFormatException (too many digits)
139```
140
141#### Immutability & chaining
142
143The `BigInteger`, `BigDecimal` and `BigRational` classes are immutable: their value never changes,
144so that they can be safely passed around. All methods that return a `BigInteger`, `BigDecimal` or `BigRational`
145return a new object, leaving the original object unaffected:
146
147```php
148$ten = BigInteger::of(10);
149
150echo $ten->plus(5); // 15
151echo $ten->multipliedBy(3); // 30
152```
153
154The methods can be chained for better readability:
155
156```php
157echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45
158```
159
160#### Parameter types
161
162All methods that accept a number: `plus()`, `minus()`, `multipliedBy()`, etc. accept the same types as `of()`.
163For example, given the following number:
164
165```php
166$integer = BigInteger::of(123);
167```
168
169The following lines are equivalent:
170
171```php
172$integer->multipliedBy(123);
173$integer->multipliedBy('123');
174$integer->multipliedBy($integer);
175```
176
177Just like `of()`, other types of `BigNumber` are acceptable, as long as they can be safely converted to the current type:
178
179```php
180echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.0')); // 4
181echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.5')); // RoundingNecessaryException
182echo BigDecimal::of(2.5)->multipliedBy(BigInteger::of(2)); // 5.0
183```
184
185These parameters are converted with `of()`, so the same rules apply: for untrusted strings, use
186[`parse()`](#parsing-untrusted-input) first, and pass the resulting number to the method.
187
188#### Division & rounding
189
190##### BigInteger
191
192By default, dividing a `BigInteger` returns the exact result of the division, or throws an exception if the remainder
193of the division is not zero:
194
195```php
196echo BigInteger::of(999)->dividedBy(3); // 333
197echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException
198```
199
200You can pass an optional [rounding mode](https://github.com/brick/math/blob/0.20.0/src/RoundingMode.php) to round the result, if necessary:
201
202```php
203echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Down); // 333
204echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Up); // 334
205```
206
207If you're into quotients and remainders, there are methods for this, too:
208
209```php
210echo BigInteger::of(1000)->quotient(3); // 333
211echo BigInteger::of(1000)->remainder(3); // 1
212```
213
214You can even get both at the same time:
215
216```php
217[$quotient, $remainder] = BigInteger::of(1000)->quotientAndRemainder(3);
218```
219
220##### BigDecimal
221
222Dividing a `BigDecimal` always requires a scale to be specified. If the exact result of the division does not fit in
223the given scale, a [rounding mode](https://github.com/brick/math/blob/0.20.0/src/RoundingMode.php) must be provided.
224
225```php
226echo BigDecimal::of(1)->dividedBy('8', 3); // 0.125
227echo BigDecimal::of(1)->dividedBy('8', 2); // RoundingNecessaryException
228echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfDown); // 0.12
229echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfUp); // 0.13
230```
231
232If you know that the division yields a finite number of decimals places, you can use `dividedByExact()`, which will
233automatically compute the required scale to fit the result, or throw an exception if the division yields an infinite
234repeating decimal:
235
236```php
237echo BigDecimal::of(1)->dividedByExact(256); // 0.00390625
238echo BigDecimal::of(1)->dividedByExact(11); // RoundingNecessaryException
239```
240
241##### BigRational
242
243The result of the division of a `BigRational` can always be represented exactly:
244
245```php
246echo BigRational::of('13/99')->dividedBy('7'); // 13/693
247echo BigRational::of('13/99')->dividedBy('9/8'); // 104/891
248```
249
250#### Bitwise operations
251
252`BigInteger` supports bitwise operations:
253
254- `and()`
255- `or()`
256- `xor()`
257- `not()`
258
259and bit shifting:
260
261- `shiftedLeft()`
262- `shiftedRight()`
263
264#### Exceptions
265
266All exceptions thrown by this library implement the `MathException` interface.
267This means that you can safely catch all exceptions thrown by this library using a single catch clause:
268
269```php
270use Brick\Math\BigDecimal;
271use Brick\Math\Exception\MathException;
272
273try {
274 $number = BigInteger::of(1)->dividedBy(3);
275} catch (MathException $e) {
276 // ...
277}
278```
279
280If you need more granular control over the exceptions thrown, you can catch the specific exception classes:
281
282- `DivisionByZeroException`
283- `IntegerOverflowException`
284- `InvalidArgumentException`
285- `NegativeNumberException`
286- `NoInverseException`
287- `NumberFormatException`
288- `PlatformException`
289- `RandomSourceException`
290- `RoundingNecessaryException`
291
292#### Serialization
293
294`BigInteger`, `BigDecimal` and `BigRational` can be safely serialized on a machine and unserialized on another,
295even if these machines do not share the same set of PHP extensions.
296
297For example, serializing on a machine with GMP support and unserializing on a machine that does not have this extension
298installed will still work as expected.
299
300#### PHPStan extension
301
302A third-party [PHPStan extension](https://github.com/simPod/phpstan-brick-math) is available for this library. It provides more specific throw type narrowing for brick/math methods, so that PHPStan can infer the exact exception classes thrown. Note that this extension is not maintained by the author of brick/math.