Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

827
vendor/brick/math/CHANGELOG.md vendored Normal file
View file

@ -0,0 +1,827 @@
# Changelog
All notable changes to this project will be documented in this file.
## [1.0.0](https://github.com/brick/math/releases/tag/1.0.0) - 2026-09-12
**First stable release** 🎉
No changes from version `0.20.0`.
## [0.20.0](https://github.com/brick/math/releases/tag/0.20.0) - 2026-08-28
💥 **Breaking changes**
- Deprecated exception class `UnsupportedPlatformException` has been removed, catch `PlatformException` instead
The following breaking change only affects you if you specifically catch `DivisionByZeroException` around calls to `of()` or to any method accepting strings:
- `of()` now throws `NumberFormatException` instead of `DivisionByZeroException` when the string is a fraction with a denominator of zero, such as `'2/0'`
✨ **New features**
- New methods: `parse()` and `parseNullable()` safely parse untrusted input, by restricting the allowed syntax and limiting the number of digits
- New enum: `NumberSyntax` lists the syntax features that `parse()` can accept, with constants for the most common combinations
🐛 **Bug fixes**
- `of()` no longer throws `PlatformException` on malformed input with many digits, crafted to trigger heavy backtracking in its parser; such input now throws `NumberFormatException` as documented
👌 **Improvements**
- `NumberFormatException` messages now escape control and non-ASCII characters, and truncate values longer than 40 bytes, instead of copying the raw input into the message
## [0.19.1](https://github.com/brick/math/releases/tag/0.19.1) - 2026-08-08
✨ **New features**
- New exception class: `PlatformException` (replaces `UnsupportedPlatformException`)
- `PlatformException` is now thrown when `preg_match()` fails due to improper PHP configuration
- `PlatformException` is now thrown when `PHP_INT_SIZE` is an unsupported value
🗑️ **Deprecations**
- Exception class `UnsupportedPlatformException` is deprecated; catch `PlatformException` instead
## [0.19.0](https://github.com/brick/math/releases/tag/0.19.0) - 2026-07-30
✨ **New features**
- New rounding mode: `RoundingMode::HalfOdd`
- New method: `RoundingMode::fromNativeRoundingMode()` converts from a native PHP `RoundingMode` enum (PHP 8.4+)
## [0.18.0](https://github.com/brick/math/releases/tag/0.18.0) - 2026-06-14
💥 **Breaking changes**
The following breaking change only affects you if you're using named arguments:
- `BigInteger::fromBytes()` now uses `$bytes` as the parameter name
🐛 **Bug fixes**
- `of()` no longer accepts a trailing newline (`\n`) in the input string; such input now throws `NumberFormatException`
- `of()` now consistently throws `NumberFormatException` for exponents too large to process, instead of `IntegerOverflowException` in some cases
- `BigInteger::fromBase()` now reports the invalid character with its original case in the `NumberFormatException` message, instead of lower-casing it
⚡️ **Performance improvements**
- `BigInteger::gcd()` no longer exhausts memory on large inputs when the GMP extension is not installed
- `BigInteger::modInverse()` no longer exhausts memory on large inputs, and is faster when the GMP extension is not installed
👌 **Static analysis improvements**
- Narrowed parameter and return types with static analysis annotations:
- `nthRoot()`'s `$n` is now `positive-int`
- `BigInteger::toBase()`, `toArbitraryBase()`, `toBytes()` and `BigRational::toRepeatingDecimalString()` now return `non-empty-string`
## [0.17.2](https://github.com/brick/math/releases/tag/0.17.2) - 2026-05-25
✨ **New features**
- New methods: `BigInteger::nthRoot()` and `BigDecimal::nthRoot()` compute the nth root of a number (#113 by @Pablo1Gustavo)
## [0.17.1](https://github.com/brick/math/releases/tag/0.17.1) - 2026-04-19
👌 **Improvements**
- More precise `float` approximations in `BigRational::toFloat()`
## [0.17.0](https://github.com/brick/math/releases/tag/0.17.0) - 2026-03-17
💥 **Breaking changes**
- Deprecated method `BigDecimal::hasNonZeroFractionalPart()` has been removed, use `! $number->getFractionalPart()->isZero()` instead
- Exception constructors and factory methods are now `@internal`
✨ **Compatibility improvements**
- `BigDecimal::fromFloatExact()` now supports 32-bit PHP
## [0.16.2](https://github.com/brick/math/releases/tag/0.16.2) - 2026-03-15
✨ **New features**
New methods to create a `BigDecimal` from a `float` value:
- `BigDecimal::fromFloatExact()`
- `BigDecimal::fromFloatShortest()`
## [0.16.1](https://github.com/brick/math/releases/tag/0.16.1) - 2026-03-09
👌 **Improvements**
- Add `@return non-empty-string` to `toString()`, `jsonSerialize()` and `__toString()` (#111 by @vudaltsov)
## [0.16.0](https://github.com/brick/math/releases/tag/0.16.0) - 2026-03-06
💥 **Breaking changes**
- **`BigInteger::getLowestSetBit()` now returns `null` instead of `-1` when the number is zero**
- Deprecated method `BigRational::simplified()` has been removed, as it is now a no-op
✨ **New features**
- New method: `BigDecimal::getIntegralPart()` returns the integral part as `BigInteger` (this method existed with a different signature in version 0.14, and was removed in 0.15)
- New method: `BigDecimal::getFractionalPart()` returns the fractional part as `BigDecimal` (this method existed with a different signature and meaning in version 0.14, and was removed in 0.15)
🗑️ **Deprecations**
- Method `BigDecimal::hasNonZeroFractionalPart()` is deprecated, use `->getFractionalPart()->isZero()` instead
## [0.15.0](https://github.com/brick/math/releases/tag/0.15.0) - 2026-02-20
💥 **Breaking changes**
- **floating-point inputs are no longer accepted by `of()` and arithmetic methods**, use `of((string) $float)` to get the same behaviour as before (#105)
- **`BigRational` is now always simplified to lowest terms:** all operations, including `of()` and `ofFraction()`, now return a fraction in its simplest form (e.g. `2/3` instead of `4/6`)
- **`BigDecimal::dividedBy()` now requires the `$scale` parameter**
- **`BigInteger::sqrt()` and `BigDecimal::sqrt()` now default to `RoundingMode::Unnecessary`**, explicitly pass `RoundingMode::Down` to get the previous behaviour
- **`BigInteger::mod()` now uses Euclidean modulo semantics**: the modulus must be strictly positive, and the result is always non-negative; this change aligns with Java's `BigInteger.mod()` behaviour
- **`BigInteger::mod()`, `modInverse()` and `modPow()` now throw `InvalidArgumentException` (instead of `NegativeNumberException`) for negative modulus/exponent arguments**
- **`MathException` is now an interface** instead of a class
- **`BigDecimal::getPrecision()` now returns `1` for zero values**
- `BigNumber::min()`, `max()` and `sum()` now throw an `ArgumentCountError` when called with no arguments (previously threw `InvalidArgumentException`)
- `BigInteger::randomBits()` and `randomRange()` now throw `RandomSourceException` when random byte generation fails or returns invalid data
Deprecated API elements removed:
- deprecated method `BigInteger::testBit()` has been removed, use `isBitSet()` instead
- deprecated method `BigInteger::gcdMultiple()` has been removed, use `gcdAll()` instead
- deprecated method `BigDecimal::exactlyDividedBy()` has been removed, use `dividedByExact()` instead
- deprecated method `BigDecimal::getIntegralPart()` has been removed (will be re-introduced as returning `BigInteger` in 0.16)
- deprecated method `BigDecimal::getFractionalPart()` has been removed (will be re-introduced as returning `BigDecimal` with a different meaning in 0.16)
- deprecated method `BigDecimal::stripTrailingZeros()` has been removed, use `strippedOfTrailingZeros()` instead
- deprecated method `BigRational::nd()` has been removed, use `ofFraction()` instead
- deprecated method `BigRational::quotient()` has been removed, use `getIntegralPart()` instead
- deprecated method `BigRational::remainder()` has been removed, use `$number->getNumerator()->remainder($number->getDenominator())` instead
- deprecated method `BigRational::quotientAndRemainder()` has been removed, use `$number->getNumerator()->quotientAndRemainder($number->getDenominator())` instead
- deprecated `RoundingMode` upper snake case constants (e.g. `HALF_UP`) have been removed, use the pascal case version (e.g. `HalfUp`) instead
The following breaking changes only affect you if you're using named arguments:
- `BigInteger::mod()` now uses `$modulus` as the parameter name
- `BigInteger::modInverse()` now uses `$modulus` as the parameter name
- `BigInteger::modPow()` now uses `$exponent` and `$modulus` as parameter names
- `BigInteger::shiftedLeft()` now uses `$bits` as the parameter name
- `BigInteger::shiftedRight()` now uses `$bits` as the parameter name
- `BigInteger::isBitSet()` now uses `$bitIndex` as the parameter name
- `BigInteger::randomBits()` now uses `$bitCount` as the parameter name
- `BigDecimal::withPointMovedLeft()` now uses `$places` as the parameter name
- `BigDecimal::withPointMovedRight()` now uses `$places` as the parameter name
The following breaking changes are unlikely to affect you:
- `DivisionByZeroException::modulusMustNotBeZero()` has been renamed to `zeroModulus()`
- `DivisionByZeroException::denominatorMustNotBeZero()` has been renamed to `zeroDenominator()`
- `IntegerOverflowException::toIntOverflow()` has been renamed to `integerOutOfRange()`
- `RoundingNecessaryException::roundingNecessary()` has been removed
🗑️ **Deprecations**
- Method `BigRational::simplified()` is deprecated, as it is now a no-op
✨ **New features**
- `BigInteger::power()`, `BigDecimal::power()` and `BigRational::power()` no longer enforce an exponent limit
- `BigInteger::shiftedLeft()` and `BigInteger::shiftedRight()` no longer enforce a limit on the number of bits
- `BigRational::power()` now accepts negative exponents
- New exception: `InvalidArgumentException` for invalid argument errors
- New exception: `NoInverseException` for modular inverse errors
- New exception: `RandomSourceException` for random source errors
👌 **Improvements**
- Narrowed parameter and return types with static analysis annotations (#108 by @simPod)
## [0.14.8](https://github.com/brick/math/releases/tag/0.14.8) - 2026-02-10
🗑️ **Deprecations**
- Method `BigInteger::testBit()` is deprecated, use `isBitSet()` instead
✨ **New features**
- New method: `BigInteger::isBitSet()` (replaces `testBit()`)
- New method: `BigNumber::toString()` (alias of magic method `__toString()`)
👌 **Improvements**
- Performance optimization of `BigRational` comparison methods
- More exceptions have been documented with `@throws` annotations
## [0.14.7](https://github.com/brick/math/releases/tag/0.14.7) - 2026-02-07
✨ **New features**
- `clamp()` is now available on the base `BigNumber` class
👌 **Improvements**
- Improved `@throws` exception documentation
## [0.14.6](https://github.com/brick/math/releases/tag/0.14.6) - 2026-02-05
🗑️ **Deprecations**
- Not passing a `$scale` to `BigDecimal::dividedBy()` is deprecated; **`$scale` will be required in 0.15**
👌 **Improvements**
- `BigRational::toFloat()` never returns `NAN` anymore
## [0.14.5](https://github.com/brick/math/releases/tag/0.14.5) - 2026-02-03
🗑️ **Deprecations**
- Not passing a rounding mode to `BigInteger::sqrt()` and `BigDecimal::sqrt()` triggers a deprecation notice: **the default rounding mode will change from `Down` to `Unnecessary` in 0.15**
✨ **New features**
- `BigInteger::sqrt()` and `BigDecimal::sqrt()` now support rounding
- `abs()` and `negated()` methods are now available on the base `BigNumber` class
👌 **Improvements**
- Alphabet is now checked for duplicate characters in `BigInteger::(from|to)ArbitraryBase()`
- `BigNumber::ofNullable()` is now marked as `@pure`
## [0.14.4](https://github.com/brick/math/releases/tag/0.14.4) - 2026-02-02
🗑️ **Deprecations**
- Passing a negative modulus to `BigInteger::mod()` is deprecated to align with Euclidean modulo semantics; it will throw `InvalidArgumentException` in 0.15
- Method `BigDecimal::stripTrailingZeros()` is deprecated, use `strippedOfTrailingZeros()` instead
✨ **New features**
- `BigInteger::modPow()` now accepts negative bases
- New method: `BigDecimal::strippedOfTrailingZeros()` (replaces `stripTrailingZeros()`)
👌 **Improvements**
- `clamp()` methods are now marked as `@pure`
## [0.14.3](https://github.com/brick/math/releases/tag/0.14.3) - 2026-02-01
✨ **New features**
- New method: `BigInteger::lcm()`
- New method: `BigInteger::lcmAll()`
- New method: `BigRational::toRepeatingDecimalString()`
🐛 **Bug fixes**
- `BigInteger::gcdAll()` / `gcdMultiple()` could return a negative result when used with a single negative number
## [0.14.2](https://github.com/brick/math/releases/tag/0.14.2) - 2026-01-30
🗑️ **Deprecations**
- **Passing `float` values to `of()` or arithmetic methods is deprecated** and will be removed in 0.15; cast to string explicitly to preserve the previous behaviour (#105)
- **Accessing `RoundingMode` enum cases through upper snake case (e.g. `HALF_UP`) is deprecated**, use the pascal case version (e.g. `HalfUp`) instead
- Method `BigInteger::gcdMultiple()` is deprecated, use `gcdAll()` instead
- Method `BigDecimal::exactlyDividedBy()` is deprecated, use `dividedByExact()` instead
- Method `BigDecimal::getIntegralPart()` is deprecated (will be removed in 0.15, and re-introduced as returning `BigInteger` in 0.16)
- Method `BigDecimal::getFractionalPart()` is deprecated (will be removed in 0.15, and re-introduced as returning `BigDecimal` with a different meaning in 0.16)
- Method `BigRational::nd()` is deprecated, use `ofFraction()` instead
- Method `BigRational::quotient()` is deprecated, use `getIntegralPart()` instead
- Method `BigRational::remainder()` is deprecated, use `$number->getNumerator()->remainder($number->getDenominator())` instead
- Method `BigRational::quotientAndRemainder()` is deprecated, use `$number->getNumerator()->quotientAndRemainder($number->getDenominator())` instead
✨ **New features**
- New method: `BigInteger::gcdAll()` (replaces `gcdMultiple()`)
- New method: `BigRational::clamp()`
- New method: `BigRational::ofFraction()` (replaces `nd()`)
- New method: `BigRational::getIntegralPart()` (replaces `quotient()`)
- New method: `BigRational::getFractionalPart()`
👌 **Improvements**
- All exceptions thrown by the library now implement a common `MathException` interface
- `BigInteger::modInverse()` now accepts `BigNumber|int|float|string` instead of just `BigInteger`
- `BigInteger::gcdMultiple()` now accepts `BigNumber|int|float|string` instead of just `BigInteger`
🐛 **Bug fixes**
- `BigInteger::clamp()` and `BigDecimal::clamp()` now throw an exception on inverted bounds, instead of returning an incorrect result
## [0.14.1](https://github.com/brick/math/releases/tag/0.14.1) - 2025-11-24
✨ **New features**
- New method: `BigNumber::ofNullable()` (#94 by @mrkh995)
✨ **Compatibility fixes**
- Fixed warnings on PHP 8.5 (#101 and #102 by @julien-boudry)
## [0.14.0](https://github.com/brick/math/releases/tag/0.14.0) - 2025-08-29
✨ **New features**
- New methods: `BigInteger::clamp()` and `BigDecimal::clamp()` (#96 by @JesterIruka)
✨ **Improvements**
- All pure methods in `BigNumber` classes are now marked as `@pure` for better static analysis
💥 **Breaking changes**
- Minimum PHP version is now 8.2
- `BigNumber` classes are now `readonly`
- `BigNumber` is now marked as sealed: it must not be extended outside of this package
- Exception classes are now `final`
## [0.13.1](https://github.com/brick/math/releases/tag/0.13.1) - 2025-03-29
✨ **Improvements**
- `__toString()` methods of `BigInteger` and `BigDecimal` are now type-hinted as returning `numeric-string` instead of `string` (#90 by @vudaltsov)
## [0.13.0](https://github.com/brick/math/releases/tag/0.13.0) - 2025-03-03
💥 **Breaking changes**
- `BigDecimal::ofUnscaledValue()` no longer throws an exception if the scale is negative
- `MathException` now extends `RuntimeException` instead of `Exception`; this reverts the change introduced in version `0.11.0` (#82)
✨ **New features**
- `BigDecimal::ofUnscaledValue()` allows a negative scale (and converts the values to create a zero scale number)
## [0.12.3](https://github.com/brick/math/releases/tag/0.12.3) - 2025-02-28
✨ **New features**
- `BigDecimal::getPrecision()` Returns the number of significant digits in a decimal number
## [0.12.2](https://github.com/brick/math/releases/tag/0.12.2) - 2025-02-26
⚡️ **Performance improvements**
- Division in `NativeCalculator` is now faster for small divisors, thanks to [@Izumi-kun](https://github.com/Izumi-kun) in [#87](https://github.com/brick/math/pull/87).
👌 **Improvements**
- Add missing `RoundingNecessaryException` to the `@throws` annotation of `BigNumber::of()`
## [0.12.1](https://github.com/brick/math/releases/tag/0.12.1) - 2023-11-29
⚡️ **Performance improvements**
- `BigNumber::of()` is now faster, thanks to [@SebastienDug](https://github.com/SebastienDug) in [#77](https://github.com/brick/math/pull/77).
## [0.12.0](https://github.com/brick/math/releases/tag/0.12.0) - 2023-11-26
💥 **Breaking changes**
- Minimum PHP version is now 8.1
- `RoundingMode` is now an `enum`; if you're type-hinting rounding modes, you need to type-hint against `RoundingMode` instead of `int` now
- `BigNumber` classes do not implement the `Serializable` interface anymore (they use the [new custom object serialization mechanism](https://wiki.php.net/rfc/custom_object_serialization))
- The following breaking changes only affect you if you're creating your own `BigNumber` subclasses:
- the return type of `BigNumber::of()` is now `static`
- `BigNumber` has a new abstract method `from()`
- all `public` and `protected` functions of `BigNumber` are now `final`
## [0.11.0](https://github.com/brick/math/releases/tag/0.11.0) - 2023-01-16
💥 **Breaking changes**
- Minimum PHP version is now 8.0
- Methods accepting a union of types are now strongly typed<sup>*</sup>
- `MathException` now extends `Exception` instead of `RuntimeException`
<sup>* You may now run into type errors if you were passing `Stringable` objects to `of()` or any of the methods
internally calling `of()`, with `strict_types` enabled. You can fix this by casting `Stringable` objects to `string`
first.</sup>
## [0.10.2](https://github.com/brick/math/releases/tag/0.10.2) - 2022-08-11
👌 **Improvements**
- `BigRational::toFloat()` now simplifies the fraction before performing division (#73) thanks to @olsavmic
## [0.10.1](https://github.com/brick/math/releases/tag/0.10.1) - 2022-08-02
✨ **New features**
- `BigInteger::gcdMultiple()` returns the GCD of multiple `BigInteger` numbers
## [0.10.0](https://github.com/brick/math/releases/tag/0.10.0) - 2022-06-18
💥 **Breaking changes**
- Minimum PHP version is now 7.4
## [0.9.3](https://github.com/brick/math/releases/tag/0.9.3) - 2021-08-15
🚀 **Compatibility with PHP 8.1**
- Support for custom object serialization; this removes a warning on PHP 8.1 due to the `Serializable` interface being deprecated (#60) thanks @TRowbotham
## [0.9.2](https://github.com/brick/math/releases/tag/0.9.2) - 2021-01-20
🐛 **Bug fix**
- Incorrect results could be returned when using the BCMath calculator, with a default scale set with `bcscale()`, on PHP >= 7.2 (#55).
## [0.9.1](https://github.com/brick/math/releases/tag/0.9.1) - 2020-08-19
✨ **New features**
- `BigInteger::not()` returns the bitwise `NOT` value
🐛 **Bug fixes**
- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers
- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available
## [0.9.0](https://github.com/brick/math/releases/tag/0.9.0) - 2020-08-18
👌 **Improvements**
- `BigNumber::of()` now accepts `.123` and `123.` formats, both of which return a `BigDecimal`
💥 **Breaking changes**
- Deprecated method `BigInteger::powerMod()` has been removed - use `modPow()` instead
- Deprecated method `BigInteger::parse()` has been removed - use `fromBase()` instead
## [0.8.17](https://github.com/brick/math/releases/tag/0.8.17) - 2020-08-19
🐛 **Bug fix**
- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers
- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available
## [0.8.16](https://github.com/brick/math/releases/tag/0.8.16) - 2020-08-18
🚑 **Critical fix**
- This version reintroduces the deprecated `BigInteger::parse()` method, that has been removed by mistake in version `0.8.9` and should have lasted for the whole `0.8` release cycle.
✨ **New features**
- `BigInteger::modInverse()` calculates a modular multiplicative inverse
- `BigInteger::fromBytes()` creates a `BigInteger` from a byte string
- `BigInteger::toBytes()` converts a `BigInteger` to a byte string
- `BigInteger::randomBits()` creates a pseudo-random `BigInteger` of a given bit length
- `BigInteger::randomRange()` creates a pseudo-random `BigInteger` between two bounds
💩 **Deprecations**
- `BigInteger::powerMod()` is now deprecated in favour of `modPow()`
## [0.8.15](https://github.com/brick/math/releases/tag/0.8.15) - 2020-04-15
🐛 **Fixes**
- added missing `ext-json` requirement, due to `BigNumber` implementing `JsonSerializable`
⚡️ **Optimizations**
- additional optimization in `BigInteger::remainder()`
## [0.8.14](https://github.com/brick/math/releases/tag/0.8.14) - 2020-02-18
✨ **New features**
- `BigInteger::getLowestSetBit()` returns the index of the rightmost one bit
## [0.8.13](https://github.com/brick/math/releases/tag/0.8.13) - 2020-02-16
✨ **New features**
- `BigInteger::isEven()` tests whether the number is even
- `BigInteger::isOdd()` tests whether the number is odd
- `BigInteger::testBit()` tests if a bit is set
- `BigInteger::getBitLength()` returns the number of bits in the minimal representation of the number
## [0.8.12](https://github.com/brick/math/releases/tag/0.8.12) - 2020-02-03
🛠️ **Maintenance release**
Classes are now annotated for better static analysis with [psalm](https://psalm.dev/).
This is a maintenance release: no bug fixes, no new features, no breaking changes.
## [0.8.11](https://github.com/brick/math/releases/tag/0.8.11) - 2020-01-23
✨ **New feature**
`BigInteger::powerMod()` performs a power-with-modulo operation. Useful for crypto.
## [0.8.10](https://github.com/brick/math/releases/tag/0.8.10) - 2020-01-21
✨ **New feature**
`BigInteger::mod()` returns the **modulo** of two numbers. The *modulo* differs from the *remainder* when the signs of the operands are different.
## [0.8.9](https://github.com/brick/math/releases/tag/0.8.9) - 2020-01-08
⚡️ **Performance improvements**
A few additional optimizations in `BigInteger` and `BigDecimal` when one of the operands can be returned as is. Thanks to @tomtomsen in #24.
## [0.8.8](https://github.com/brick/math/releases/tag/0.8.8) - 2019-04-25
🐛 **Bug fixes**
- `BigInteger::toBase()` could return an empty string for zero values (BCMath & Native calculators only, GMP calculator unaffected)
✨ **New features**
- `BigInteger::toArbitraryBase()` converts a number to an arbitrary base, using a custom alphabet
- `BigInteger::fromArbitraryBase()` converts a string in an arbitrary base, using a custom alphabet, back to a number
These methods can be used as the foundation to convert strings between different bases/alphabets, using BigInteger as an intermediate representation.
💩 **Deprecations**
- `BigInteger::parse()` is now deprecated in favour of `fromBase()`
`BigInteger::fromBase()` works the same way as `parse()`, with 2 minor differences:
- the `$base` parameter is required, it does not default to `10`
- it throws a `NumberFormatException` instead of an `InvalidArgumentException` when the number is malformed
## [0.8.7](https://github.com/brick/math/releases/tag/0.8.7) - 2019-04-20
**Improvements**
- Safer conversion from `float` when using custom locales
- **Much faster** `NativeCalculator` implementation 🚀
You can expect **at least a 3x performance improvement** for common arithmetic operations when using the library on systems without GMP or BCMath; it gets exponentially faster on multiplications with a high number of digits. This is due to calculations now being performed on whole blocks of digits (the block size depending on the platform, 32-bit or 64-bit) instead of digit-by-digit as before.
## [0.8.6](https://github.com/brick/math/releases/tag/0.8.6) - 2019-04-11
**New method**
`BigNumber::sum()` returns the sum of one or more numbers.
## [0.8.5](https://github.com/brick/math/releases/tag/0.8.5) - 2019-02-12
**Bug fix**: `of()` factory methods could fail when passing a `float` in environments using a `LC_NUMERIC` locale with a decimal separator other than `'.'` (#20).
Thanks @manowark 👍
## [0.8.4](https://github.com/brick/math/releases/tag/0.8.4) - 2018-12-07
**New method**
`BigDecimal::sqrt()` calculates the square root of a decimal number, to a given scale.
## [0.8.3](https://github.com/brick/math/releases/tag/0.8.3) - 2018-12-06
**New method**
`BigInteger::sqrt()` calculates the square root of a number (thanks @peter279k).
**New exception**
`NegativeNumberException` is thrown when calling `sqrt()` on a negative number.
## [0.8.2](https://github.com/brick/math/releases/tag/0.8.2) - 2018-11-08
**Performance update**
- Further improvement of `toInt()` performance
- `NativeCalculator` can now perform some multiplications more efficiently
## [0.8.1](https://github.com/brick/math/releases/tag/0.8.1) - 2018-11-07
Performance optimization of `toInt()` methods.
## [0.8.0](https://github.com/brick/math/releases/tag/0.8.0) - 2018-10-13
**Breaking changes**
The following deprecated methods have been removed. Use the new method name instead:
| Method removed | Replacement method |
| --- | --- |
| `BigDecimal::getIntegral()` | `BigDecimal::getIntegralPart()` |
| `BigDecimal::getFraction()` | `BigDecimal::getFractionalPart()` |
---
**New features**
`BigInteger` has been augmented with 5 new methods for bitwise operations:
| New method | Description |
| --- | --- |
| `and()` | performs a bitwise `AND` operation on two numbers |
| `or()` | performs a bitwise `OR` operation on two numbers |
| `xor()` | performs a bitwise `XOR` operation on two numbers |
| `shiftedLeft()` | returns the number shifted left by a number of bits |
| `shiftedRight()` | returns the number shifted right by a number of bits |
Thanks to @DASPRiD 👍
## [0.7.3](https://github.com/brick/math/releases/tag/0.7.3) - 2018-08-20
**New method:** `BigDecimal::hasNonZeroFractionalPart()`
**Renamed/deprecated methods:**
- `BigDecimal::getIntegral()` has been renamed to `getIntegralPart()` and is now deprecated
- `BigDecimal::getFraction()` has been renamed to `getFractionalPart()` and is now deprecated
## [0.7.2](https://github.com/brick/math/releases/tag/0.7.2) - 2018-07-21
**Performance update**
`BigInteger::parse()` and `toBase()` now use GMP's built-in base conversion features when available.
## [0.7.1](https://github.com/brick/math/releases/tag/0.7.1) - 2018-03-01
This is a maintenance release, no code has been changed.
- When installed with `--no-dev`, the autoloader does not autoload tests anymore
- Tests and other files unnecessary for production are excluded from the dist package
This will help make installations more compact.
## [0.7.0](https://github.com/brick/math/releases/tag/0.7.0) - 2017-10-02
Methods renamed:
- `BigNumber:sign()` has been renamed to `getSign()`
- `BigDecimal::unscaledValue()` has been renamed to `getUnscaledValue()`
- `BigDecimal::scale()` has been renamed to `getScale()`
- `BigDecimal::integral()` has been renamed to `getIntegral()`
- `BigDecimal::fraction()` has been renamed to `getFraction()`
- `BigRational::numerator()` has been renamed to `getNumerator()`
- `BigRational::denominator()` has been renamed to `getDenominator()`
Classes renamed:
- `ArithmeticException` has been renamed to `MathException`
## [0.6.2](https://github.com/brick/math/releases/tag/0.6.2) - 2017-10-02
The base class for all exceptions is now `MathException`.
`ArithmeticException` has been deprecated, and will be removed in 0.7.0.
## [0.6.1](https://github.com/brick/math/releases/tag/0.6.1) - 2017-10-02
A number of methods have been renamed:
- `BigNumber:sign()` is deprecated; use `getSign()` instead
- `BigDecimal::unscaledValue()` is deprecated; use `getUnscaledValue()` instead
- `BigDecimal::scale()` is deprecated; use `getScale()` instead
- `BigDecimal::integral()` is deprecated; use `getIntegral()` instead
- `BigDecimal::fraction()` is deprecated; use `getFraction()` instead
- `BigRational::numerator()` is deprecated; use `getNumerator()` instead
- `BigRational::denominator()` is deprecated; use `getDenominator()` instead
The old methods will be removed in version 0.7.0.
## [0.6.0](https://github.com/brick/math/releases/tag/0.6.0) - 2017-08-25
- Minimum PHP version is now [7.1](https://gophp71.org/); for PHP 5.6 and PHP 7.0 support, use version `0.5`
- Deprecated method `BigDecimal::withScale()` has been removed; use `toScale()` instead
- Method `BigNumber::toInteger()` has been renamed to `toInt()`
## [0.5.4](https://github.com/brick/math/releases/tag/0.5.4) - 2016-10-17
`BigNumber` classes now implement [JsonSerializable](http://php.net/manual/en/class.jsonserializable.php).
The JSON output is always a string.
## [0.5.3](https://github.com/brick/math/releases/tag/0.5.3) - 2016-03-31
This is a bugfix release. Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6.
## [0.5.2](https://github.com/brick/math/releases/tag/0.5.2) - 2015-08-06
The `$scale` parameter of `BigDecimal::dividedBy()` is now optional again.
## [0.5.1](https://github.com/brick/math/releases/tag/0.5.1) - 2015-07-05
**New method: `BigNumber::toScale()`**
This allows to convert any `BigNumber` to a `BigDecimal` with a given scale, using rounding if necessary.
## [0.5.0](https://github.com/brick/math/releases/tag/0.5.0) - 2015-07-04
**New features**
- Common `BigNumber` interface for all classes, with the following methods:
- `sign()` and derived methods (`isZero()`, `isPositive()`, ...)
- `compareTo()` and derived methods (`isEqualTo()`, `isGreaterThan()`, ...) that work across different `BigNumber` types
- `toBigInteger()`, `toBigDecimal()`, `toBigRational`() conversion methods
- `toInteger()` and `toFloat()` conversion methods to native types
- Unified `of()` behaviour: every class now accepts any type of number, provided that it can be safely converted to the current type
- New method: `BigDecimal::exactlyDividedBy()`; this method automatically computes the scale of the result, provided that the division yields a finite number of digits
- New methods: `BigRational::quotient()` and `remainder()`
- Fine-grained exceptions: `DivisionByZeroException`, `RoundingNecessaryException`, `NumberFormatException`
- Factory methods `zero()`, `one()` and `ten()` available in all classes
- Rounding mode reintroduced in `BigInteger::dividedBy()`
This release also comes with many performance improvements.
---
**Breaking changes**
- `BigInteger`:
- `getSign()` is renamed to `sign()`
- `toString()` is renamed to `toBase()`
- `BigInteger::dividedBy()` now throws an exception by default if the remainder is not zero; use `quotient()` to get the previous behaviour
- `BigDecimal`:
- `getSign()` is renamed to `sign()`
- `getUnscaledValue()` is renamed to `unscaledValue()`
- `getScale()` is renamed to `scale()`
- `getIntegral()` is renamed to `integral()`
- `getFraction()` is renamed to `fraction()`
- `divideAndRemainder()` is renamed to `quotientAndRemainder()`
- `dividedBy()` now takes a **mandatory** `$scale` parameter **before** the rounding mode
- `toBigInteger()` does not accept a `$roundingMode` parameter anymore
- `toBigRational()` does not simplify the fraction anymore; explicitly add `->simplified()` to get the previous behaviour
- `BigRational`:
- `getSign()` is renamed to `sign()`
- `getNumerator()` is renamed to `numerator()`
- `getDenominator()` is renamed to `denominator()`
- `of()` is renamed to `nd()`, while `parse()` is renamed to `of()`
- Miscellaneous:
- `ArithmeticException` is moved to an `Exception\` sub-namespace
- `of()` factory methods now throw `NumberFormatException` instead of `InvalidArgumentException`
## [0.4.3](https://github.com/brick/math/releases/tag/0.4.3) - 2016-03-31
Backport of two bug fixes from the 0.5 branch:
- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected
- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6.
## [0.4.2](https://github.com/brick/math/releases/tag/0.4.2) - 2015-06-16
New method: `BigDecimal::stripTrailingZeros()`
## [0.4.1](https://github.com/brick/math/releases/tag/0.4.1) - 2015-06-12
Introducing a `BigRational` class, to perform calculations on fractions of any size.
## [0.4.0](https://github.com/brick/math/releases/tag/0.4.0) - 2015-06-12
Rounding modes have been removed from `BigInteger`, and are now a concept specific to `BigDecimal`.
`BigInteger::dividedBy()` now always returns the quotient of the division.
## [0.3.5](https://github.com/brick/math/releases/tag/0.3.5) - 2016-03-31
Backport of two bug fixes from the 0.5 branch:
- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected
- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6.
## [0.3.4](https://github.com/brick/math/releases/tag/0.3.4) - 2015-06-11
New methods:
- `BigInteger::remainder()` returns the remainder of a division only
- `BigInteger::gcd()` returns the greatest common divisor of two numbers
## [0.3.3](https://github.com/brick/math/releases/tag/0.3.3) - 2015-06-07
Fix `toString()` not handling negative numbers.
## [0.3.2](https://github.com/brick/math/releases/tag/0.3.2) - 2015-06-07
`BigInteger` and `BigDecimal` now have a `getSign()` method that returns:
- `-1` if the number is negative
- `0` if the number is zero
- `1` if the number is positive
## [0.3.1](https://github.com/brick/math/releases/tag/0.3.1) - 2015-06-05
Minor performance improvements
## [0.3.0](https://github.com/brick/math/releases/tag/0.3.0) - 2015-06-04
The `$roundingMode` and `$scale` parameters have been swapped in `BigDecimal::dividedBy()`.
## [0.2.2](https://github.com/brick/math/releases/tag/0.2.2) - 2015-06-04
Stronger immutability guarantee for `BigInteger` and `BigDecimal`.
So far, it would have been possible to break immutability of these classes by calling the `unserialize()` internal function. This release fixes that.
## [0.2.1](https://github.com/brick/math/releases/tag/0.2.1) - 2015-06-02
Added `BigDecimal::divideAndRemainder()`
## [0.2.0](https://github.com/brick/math/releases/tag/0.2.0) - 2015-05-22
- `min()` and `max()` do not accept an `array` anymore, but a variable number of parameters
- **minimum PHP version is now 5.6**
- continuous integration with PHP 7
## [0.1.1](https://github.com/brick/math/releases/tag/0.1.1) - 2014-09-01
- Added `BigInteger::power()`
- Added HHVM support
## [0.1.0](https://github.com/brick/math/releases/tag/0.1.0) - 2014-08-31
First beta release.

20
vendor/brick/math/LICENSE vendored Normal file
View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2013-present Benjamin Morel
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

534
vendor/brick/math/README.md vendored Normal file
View file

@ -0,0 +1,534 @@
# Brick\Math
<img src="https://raw.githubusercontent.com/brick/brick/master/logo.png" alt="" align="left" height="64">
A PHP library to work with arbitrary-precision numbers.
[![Build Status](https://github.com/brick/math/workflows/CI/badge.svg)](https://github.com/brick/math/actions)
[![Coverage Status](https://codecov.io/github/brick/math/graph/badge.svg)](https://codecov.io/github/brick/math)
[![Latest Stable Version](https://poser.pugx.org/brick/math/v/stable)](https://packagist.org/packages/brick/math)
[![Total Downloads](https://poser.pugx.org/brick/math/downloads)](https://packagist.org/packages/brick/math)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/license/MIT)
## Introduction
This library provides immutable classes to work with three types of numbers:
- `BigInteger` — an integer number such as `123`
- `BigDecimal` — a decimal number such as `1.23`
- `BigRational` — a fraction such as `2/3` — always reduced to lowest terms, e.g. `2/6` becomes `1/3`
It automatically uses GMP or BCMath when available, and falls back to a pure-PHP implementation otherwise.
All classes work with a virtually **unlimited number of digits**, and are only limited by available memory and CPU time.
### Installation
This library is installable via [Composer](https://getcomposer.org/):
```bash
composer require brick/math
```
### Requirements
This library requires PHP 8.2 or later.
Although the library can work seamlessly on any PHP installation, it is highly recommended that you install the
[GMP](https://php.net/manual/en/book.gmp.php) or [BCMath](https://php.net/manual/en/book.bc.php) extension
to speed up calculations. The fastest available calculator implementation will be automatically selected at runtime.
## Number classes
The three number classes all extend the same `BigNumber` class:
```
Brick\Math\BigNumber
├── BigInteger
├── BigDecimal
└── BigRational
```
`BigNumber` is an abstract class that defines the common behaviour of all number classes:
- `of()` — to obtain an instance
- sign methods: `isZero()`, `isPositive()`, etc.
- comparison methods: `isEqualTo()`, `isGreaterThan()`, etc.
- `min()`, `max()`, `sum()`, `toString()`, etc.
## Instantiation
The constructors of the classes are not public, so 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:
```php
BigInteger::of(123456);
BigInteger::of('9999999999999999999999999999999999999999999');
BigDecimal::of('9.99999999999999999999999999999999999999999999');
BigDecimal::of('1.23e1000');
BigRational::of('2/3');
```
The `of()` method of each class accepts all the representations above, *as long as the value can be safely converted to that class*:
```php
BigInteger::of('1e3'); // 1000
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
```
> [!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:
```php
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:
```php
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)
```
## Parameter types
All methods that accept a number (`plus()`, `minus()`, `multipliedBy()`, etc.) accept the same types as `of()`.
For example, given the following number:
```php
$integer = BigInteger::of(123);
```
The following lines are equivalent:
```php
$integer->multipliedBy(123);
$integer->multipliedBy('123');
$integer->multipliedBy($integer);
```
As with `of()`, other types of numbers are accepted, as long as they can be safely converted to the current type:
```php
echo BigInteger::of(2)->multipliedBy('2.0'); // 4
echo BigInteger::of(2)->multipliedBy('2.5'); // RoundingNecessaryException
echo BigDecimal::of('2.5')->multipliedBy(2); // 5.0
```
These parameters are converted with `of()`, so the same rules apply: for untrusted strings, use
[`parse()`](#parsing-untrusted-input) first, and pass the resulting number to the method.
## 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:
```php
$ten = BigInteger::of(10);
echo $ten->plus(5); // 15
echo $ten->multipliedBy(3); // 30
```
The methods can be chained for better readability:
```php
echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45
```
## Rounding
Unless documented otherwise, all methods either return an exact result or throw an exception if the result is not exact.
Where applicable, this behaviour is configurable through an optional `RoundingMode` parameter:
| Rounding mode | Description |
|-----------------------------|---------------------------------------------------------------|
| `RoundingMode::Unnecessary` | Requires an exact result; throws if rounding would be needed. |
| `RoundingMode::Up` | Rounds away from zero. |
| `RoundingMode::Down` | Rounds toward zero. |
| `RoundingMode::Ceiling` | Rounds toward positive infinity. |
| `RoundingMode::Floor` | Rounds toward negative infinity. |
| `RoundingMode::HalfUp` | Rounds to nearest; ties away from zero. |
| `RoundingMode::HalfDown` | Rounds to nearest; ties toward zero. |
| `RoundingMode::HalfCeiling` | Rounds to nearest; ties toward positive infinity. |
| `RoundingMode::HalfFloor` | Rounds to nearest; ties toward negative infinity. |
| `RoundingMode::HalfEven` | Rounds to nearest; ties to the even neighbor. |
| `RoundingMode::HalfOdd` | Rounds to nearest; ties to the odd neighbor. |
See the [Division](#division) section for examples of `RoundingMode` in action.
> [!TIP]
> PHP 8.4 introduced a native [RoundingMode](https://www.php.net/manual/en/enum.roundingmode.php) enum, used by
> `round()`, `bcround()` and `BcMath\Number::round()`. If you already have a native rounding mode at hand, you can
> convert it to its `Brick\Math` equivalent:
>
> ```php
> $roundingMode = RoundingMode::fromNativeRoundingMode(\RoundingMode::HalfAwayFromZero);
> ```
## Arithmetic operations
### Addition, subtraction and multiplication
These operations are straightforward on all number classes:
```php
echo BigInteger::of(1)->plus(2)->multipliedBy(3); // 9
echo BigDecimal::of('1.2')->plus('3.4')->multipliedBy('5.6'); // 25.76
echo BigRational::of('2/3')->plus('5/6')->multipliedBy('5/4'); // 15/8
```
The scale of `BigDecimal` operation results is predictable:
- for addition and subtraction, it is the larger of the two operand scales;
- for multiplication, it is the sum of the operand scales.
`BigRational` results are automatically reduced to lowest terms.
### Division
Division uses a class-specific API because exactness and precision rules differ between integers, decimals, and rationals.
#### 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:
```php
echo BigInteger::of(999)->dividedBy(3); // 333
echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException
```
You can pass an optional `RoundingMode` to round the result, if necessary:
```php
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Down); // 333
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Up); // 334
```
You can also compute quotients and remainders:
```php
echo BigInteger::of(1000)->quotient(3); // 333
echo BigInteger::of(1000)->remainder(3); // 1
```
You can also get both in one call:
```php
[$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 `RoundingMode` must be provided:
```php
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 decimal 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:
```php
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:
```php
echo BigRational::of('13/99')->dividedBy('7'); // 13/693
echo BigRational::of('13/99')->dividedBy('9/8'); // 104/891
```
`BigRational` results are automatically reduced to lowest terms.
### Other arithmetic operations
In addition to `plus()`, `minus()`, `multipliedBy()`, and `dividedBy()`, the library provides:
- exponentiation with `power()` on all number classes
- square root with `sqrt()` on `BigInteger` and `BigDecimal`
- nth root with `nthRoot()` on `BigInteger` and `BigDecimal`
- greatest common divisor / least common multiple with `gcd()`, `lcm()`, `gcdAll()`, `lcmAll()` on `BigInteger`
- modular arithmetic with `mod()`, `modInverse()`, and `modPow()` on `BigInteger`
- reciprocal with `reciprocal()` on `BigRational`
- decimal-point shifts with `withPointMovedLeft()` and `withPointMovedRight()` on `BigDecimal`
## Sign and comparison
All number classes share the same sign and comparison methods through `BigNumber`.
### Sign methods
Use these methods to inspect the sign of a number:
- `getSign()` — returns `-1`, `0`, or `1` for values `< 0`, `= 0`, and `> 0`, respectively
- `isZero()`
- `isNegative()`
- `isNegativeOrZero()`
- `isPositive()`
- `isPositiveOrZero()`
For sign-related transformations, use:
- `abs()` — returns the absolute value
- `negated()` — returns the opposite value
### Comparison methods
Comparison works across all number classes (`BigInteger`, `BigDecimal`, `BigRational`):
- `compareTo()` — returns `-1`, `0`, or `1` if this number is `<`, `=`, or `>` the given number
- `isEqualTo()`
- `isLessThan()`
- `isLessThanOrEqualTo()`
- `isGreaterThan()`
- `isGreaterThanOrEqualTo()`
You can also use `min()`, `max()`, and `clamp()` to compare and bound values.
## Type conversion
### Conversion to other number classes
All classes provide the following methods:
- `toBigInteger()`
- `toBigDecimal()`
- `toBigRational()`
`toBigInteger()` and `toBigDecimal()` either return an exact result, or throw a `RoundingNecessaryException` if the conversion is not exact.
`toBigRational()` always returns an exact result.
You can also convert any number to a `BigDecimal` with a given scale, rounding the result if necessary:
```php
echo BigRational::of('2/3')->toScale(5, RoundingMode::Up); // 0.66667
```
To convert any number to a `BigInteger` with rounding, use:
```php
echo BigRational::of('10/3')->toScale(0, RoundingMode::Up)->toBigInteger(); // 4
```
### Conversion to native numbers
All classes provide the following methods:
- `toInt()` — converts exactly to an `int` if possible, or throws an exception otherwise
- `toFloat()` — returns an approximation of the number as a `float` (may be infinite)
> [!WARNING]
> `toFloat()` is the only method of the library that returns an approximation. Use it with caution.
### Conversion to string
All number classes can be converted to string using either the `toString()` method or the `(string)` cast. For example, the following lines are equivalent:
```php
echo BigInteger::of(123)->toString();
echo (string) BigInteger::of(123);
```
Different number classes produce different outputs. Note that a `BigDecimal` with a scale of zero and a `BigRational` with a denominator of one both print as plain digit strings:
```php
echo BigInteger::of(-123)->toString(); // -123
echo BigDecimal::of('1.0')->toString(); // 1.0
echo BigDecimal::of('1')->toString(); // 1
echo BigRational::of('2/3')->toString(); // 2/3
echo BigRational::of('1/1')->toString(); // 1
```
All string outputs are parseable by the `of()` factory method. The following is guaranteed to work:
```php
BigNumber::of($bigNumber->toString());
```
> [!IMPORTANT]
> Because `BigDecimal::toString()` and `BigRational::toString()` can return whole numbers, these numbers will be parsed
> as `BigInteger` when using `BigNumber::of()`. If you want to retain the original type when reparsing numbers, be sure
> to use `of()` on the specific class: `BigDecimal::of()` or `BigRational::of()`.
#### BigRational to decimal string
In addition to the standard rational representation such as `2/3`, rational numbers can be represented as decimal numbers
with a potentially repeating sequence of digits. You can use `toRepeatingDecimalString()` to get this representation:
```php
BigRational::of('1/2')->toRepeatingDecimalString(); // 0.5
BigRational::of('2/3')->toRepeatingDecimalString(); // 0.(6)
BigRational::of('171/70')->toRepeatingDecimalString(); // 2.4(428571)
```
The part in parentheses is the repeating period, if any.
> [!NOTE]
> The `of()` and `parse()` factory methods do not accept decimal strings with repeating periods.
> [!WARNING]
> `BigRational::toRepeatingDecimalString()` is unbounded.
> The repeating period can be as large as `denominator - 1`, so large denominators can require a lot of memory and CPU time.
> Example: `BigRational::of('1/100019')->toRepeatingDecimalString()` has a repeating period of 100,018 digits.
## Base conversion
`BigInteger` can parse and format numbers in different bases:
- `fromBase()` / `toBase()` for bases 2 to 36 (case-insensitive input, lowercase output above base 10)
- `fromArbitraryBase()` / `toArbitraryBase()` for custom single-byte alphabets
```php
echo BigInteger::fromBase('ff', 16); // 255
echo BigInteger::of(255)->toBase(16); // ff
echo BigInteger::fromArbitraryBase('bab', 'ab'); // 5
echo BigInteger::of(5)->toArbitraryBase('ab'); // bab
```
You can also convert to and from byte strings using `fromBytes()` and `toBytes()`.
## Bitwise operations
`BigInteger` supports bitwise operations:
- `and()`
- `or()`
- `xor()`
- `not()`
and bit shifting:
- `shiftedLeft()`
- `shiftedRight()`
Bit-level inspection helpers are also available:
- `getBitLength()`
- `getLowestSetBit()`
- `isBitSet()`
## Random number generation
`BigInteger` provides factory methods for random integers:
- `randomBits($bitCount)` returns a non-negative integer with up to the requested bit length.
- `randomRange($min, $max)` returns a value in the inclusive range `[$min, $max]`.
Both methods use a secure random source by default and throw `RandomSourceException` if randomness cannot be obtained.
## 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:
```php
use Brick\Math\BigInteger;
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 documented in each method:
- `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.
### JSON
All number classes support serialization to JSON using the `json_encode()` function:
```php
echo json_encode(BigInteger::of(123)); // "123"
```
## Additional information
### Release process
This library follows [semantic versioning](https://semver.org/).
### PHPStan extension
A 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.

39
vendor/brick/math/composer.json vendored Normal file
View file

@ -0,0 +1,39 @@
{
"name": "brick/math",
"description": "Arbitrary-precision arithmetic library",
"type": "library",
"keywords": [
"Brick",
"Math",
"Mathematics",
"Arbitrary-precision",
"Arithmetic",
"BigInteger",
"BigDecimal",
"BigRational",
"BigNumber",
"Bignum",
"Decimal",
"Rational",
"Integer"
],
"license": "MIT",
"require": {
"php": "^8.2"
},
"require-dev": {
"phpunit/phpunit": "^11.5",
"phpstan/phpstan": "2.2.13",
"phpstan/phpstan-phpunit": "2.0.18"
},
"autoload": {
"psr-4": {
"Brick\\Math\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Brick\\Math\\Tests\\": "tests/"
}
}
}

1221
vendor/brick/math/src/BigDecimal.php vendored Normal file

File diff suppressed because it is too large Load diff

1497
vendor/brick/math/src/BigInteger.php vendored Normal file

File diff suppressed because it is too large Load diff

911
vendor/brick/math/src/BigNumber.php vendored Normal file
View file

@ -0,0 +1,911 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\IntegerOverflowException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\PlatformException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Math\Internal\Safe;
use JsonSerializable;
use Override;
use Stringable;
use function array_is_list;
use function assert;
use function filter_var;
use function in_array;
use function is_int;
use function ltrim;
use function max;
use function preg_match;
use function str_contains;
use function str_repeat;
use function strlen;
use const FILTER_VALIDATE_INT;
use const PHP_INT_MAX;
use const PREG_UNMATCHED_AS_NULL;
/**
* Base class for arbitrary-precision numbers.
*
* This class is sealed: it is part of the public API but should not be subclassed in userland.
* Protected methods may change in any version.
*
* @phpstan-sealed BigInteger|BigDecimal|BigRational
*/
abstract readonly class BigNumber implements JsonSerializable, Stringable
{
/**
* The regular expression used to parse integer or decimal numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
* The digit quantifiers must be possessive (++): backtracking on malformed input could exhaust
* pcre.backtrack_limit, surfacing as PlatformException instead of NumberFormatException.
*/
private const PARSE_REGEXP_NUMERICAL =
'/^' .
'(?<sign>[\-\+])?' .
'(?<integral>[0-9]++)?' .
'(?<point>\.)?' .
'(?<fractional>[0-9]++)?' .
'(?:[eE](?<exponent>[\-\+]?[0-9]++))?' .
'\z/';
/**
* The regular expression used to parse rational numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
* The digit quantifiers must be possessive (++): backtracking on malformed input could exhaust
* pcre.backtrack_limit, surfacing as PlatformException instead of NumberFormatException.
*/
private const PARSE_REGEXP_RATIONAL =
'/^' .
'(?<sign>[\-\+])?' .
'(?<numerator>[0-9]++)' .
'\/' .
'(?<denominator>[0-9]++)' .
'\z/';
/**
* Creates a BigNumber of the given value.
*
* When of() is called on BigNumber, the concrete return type is dependent on the given value, with the following
* rules:
*
* - BigNumber instances are returned as is
* - integer numbers are returned as BigInteger
* - strings containing a `/` character are returned as BigRational
* - strings containing a `.` character or using an exponential notation are returned as BigDecimal
* - strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger
*
* When of() is called on BigInteger, BigDecimal, or BigRational, the resulting number is converted to an instance
* of the subclass when possible; otherwise a RoundingNecessaryException is thrown.
*
* When parsing untrusted input, use {@see parse()} instead.
*
* @throws NumberFormatException If the input is a string, and the format of the number is not valid.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
*
* @pure
*/
final public static function of(BigNumber|int|string $value): static
{
$value = self::_of($value);
if ($value instanceof static) {
// No conversion needed.
return $value;
}
return static::from($value);
}
/**
* Creates a BigNumber of the given value, or returns null if the input is null.
*
* Behaves like {@see of()} for non-null values.
*
* When parsing untrusted input, use {@see parseNullable()} instead.
*
* @throws NumberFormatException If the input is a string, and the format of the number is not valid.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
*
* @pure
*/
final public static function ofNullable(BigNumber|int|string|null $value): ?static
{
if ($value === null) {
return null;
}
return static::of($value);
}
/**
* Creates a BigNumber of the given string, limiting the allowed syntax and the number of digits.
*
* This method is designed to safely parse untrusted input: huge strings, and exponential notation that allows a
* short string such as `1e1000000000` to expand to gigabytes of memory.
*
* The $allowedSyntax parameter restricts the accepted notations: plain integers such as `123` are always accepted,
* then each NumberSyntax case allows one additional feature: DecimalPoint, Exponent, Fraction. A value is accepted
* only if every feature it uses is allowed. The NumberSyntax enum also provides constants for the most common
* combinations, from NumberSyntax::INTEGER to NumberSyntax::ALL.
*
* The $maxDigits parameter limits the number of digits, counted in each of these forms:
*
* - as written, where every digit of the input counts, including leading zeros and exponent digits: `005` counts
* 3 digits, `01e-3` counts 3, and `010/012` counts 6;
* - in its expanded form, with exponents materialized and leading zeros trimmed: `01e-3` counts 4 (`0.001`);
* - in its converted form, when called on a subclass, as written by toString(): `BigDecimal::parse('1/8', ...)`
* counts 4 digits (`0.125`), although `1/8` counts only 2.
*
* When parse() is called on BigNumber, the concrete return type is determined by the format of the string,
* following the same rules as {@see of()}. When called on a subclass, the value is converted to an instance of
* that subclass when possible.
*
* @param string $value The untrusted value to parse.
* @param list<NumberSyntax> $allowedSyntax The allowed syntax features; plain integers are always accepted.
* @param positive-int $maxDigits The maximum number of digits, as written and in the resulting number.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
* @throws InvalidArgumentException If $allowedSyntax is not a list of NumberSyntax cases, or if $maxDigits is
* less than 1.
*
* @pure
*/
final public static function parse(
string $value,
array $allowedSyntax,
int $maxDigits,
): static {
if (! array_is_list($allowedSyntax)) { // @phpstan-ignore function.alreadyNarrowedType
throw InvalidArgumentException::invalidAllowedSyntax();
}
foreach ($allowedSyntax as $syntax) {
if (! $syntax instanceof NumberSyntax) { // @phpstan-ignore instanceof.alwaysTrue
throw InvalidArgumentException::invalidAllowedSyntax();
}
}
if ($maxDigits < 1) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::nonPositiveMaxDigits();
}
$value = self::_parse($value, $allowedSyntax, $maxDigits);
if ($value instanceof static) {
// No conversion needed.
return $value;
}
$result = static::from($value);
// The conversion may expand the number (1/8 -> 0.125): the limit applies to the result as well.
if ($result->digitCount() > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
return $result;
}
/**
* Creates a BigNumber of the given string, limiting the allowed syntax and the number of digits, or returns null
* if the input is null.
*
* Behaves like {@see parse()} for non-null values.
*
* @param string|null $value The untrusted value to parse, or null.
* @param list<NumberSyntax> $allowedSyntax The allowed syntax features; plain integers are always accepted.
* @param positive-int $maxDigits The maximum number of digits, as written and in the resulting number.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
* @throws InvalidArgumentException If $allowedSyntax is not a list of NumberSyntax cases, or if $maxDigits is
* less than 1.
*
* @pure
*/
final public static function parseNullable(
?string $value,
array $allowedSyntax,
int $maxDigits,
): ?static {
if ($value === null) {
if (! array_is_list($allowedSyntax)) { // @phpstan-ignore function.alreadyNarrowedType
throw InvalidArgumentException::invalidAllowedSyntax();
}
foreach ($allowedSyntax as $syntax) {
if (! $syntax instanceof NumberSyntax) { // @phpstan-ignore instanceof.alwaysTrue
throw InvalidArgumentException::invalidAllowedSyntax();
}
}
if ($maxDigits < 1) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::nonPositiveMaxDigits();
}
return null;
}
return static::parse($value, $allowedSyntax, $maxDigits);
}
/**
* Returns the minimum of the given values.
*
* If several values are equal and minimal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function min(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$min = static::of($a);
foreach ($n as $value) {
$value = static::of($value);
if ($value->isLessThan($min)) {
$min = $value;
}
}
return $min;
}
/**
* Returns the maximum of the given values.
*
* If several values are equal and maximal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function max(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$max = static::of($a);
foreach ($n as $value) {
$value = static::of($value);
if ($value->isGreaterThan($max)) {
$max = $value;
}
}
return $max;
}
/**
* Returns the sum of the given values.
*
* When called on BigNumber, sum() accepts any supported type and returns a result whose type is the widest among
* the given values (BigInteger < BigDecimal < BigRational).
*
* When called on BigInteger, BigDecimal, or BigRational, sum() requires that all values can be converted to that
* specific subclass, and returns a result of the same type.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function sum(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$sum = static::of($a);
foreach ($n as $value) {
$sum = self::add($sum, static::of($value));
}
assert($sum instanceof static);
return $sum;
}
/**
* Checks if this number is equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) === 0;
}
/**
* Checks if this number is strictly less than the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isLessThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) < 0;
}
/**
* Checks if this number is less than or equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isLessThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) <= 0;
}
/**
* Checks if this number is strictly greater than the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isGreaterThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) > 0;
}
/**
* Checks if this number is greater than or equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isGreaterThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) >= 0;
}
/**
* Checks if this number equals zero.
*
* @pure
*/
final public function isZero(): bool
{
return $this->getSign() === 0;
}
/**
* Checks if this number is strictly negative.
*
* @pure
*/
final public function isNegative(): bool
{
return $this->getSign() < 0;
}
/**
* Checks if this number is negative or zero.
*
* @pure
*/
final public function isNegativeOrZero(): bool
{
return $this->getSign() <= 0;
}
/**
* Checks if this number is strictly positive.
*
* @pure
*/
final public function isPositive(): bool
{
return $this->getSign() > 0;
}
/**
* Checks if this number is positive or zero.
*
* @pure
*/
final public function isPositiveOrZero(): bool
{
return $this->getSign() >= 0;
}
/**
* Returns the absolute value of this number.
*
* @pure
*/
final public function abs(): static
{
return $this->isNegative() ? $this->negated() : $this;
}
/**
* Returns the negated value of this number.
*
* @pure
*/
abstract public function negated(): static;
/**
* Returns the sign of this number.
*
* Returns -1 if the number is negative, 0 if zero, 1 if positive.
*
* @return -1|0|1
*
* @pure
*/
abstract public function getSign(): int;
/**
* Compares this number to the given one.
*
* Returns -1 if `$this` is lower than, 0 if equal to, 1 if greater than `$that`.
*
* @return -1|0|1
*
* @throws MathException If the number is not valid.
*
* @pure
*/
abstract public function compareTo(BigNumber|int|string $that): int;
/**
* Limits (clamps) this number between the given minimum and maximum values.
*
* If the number is lower than $min, returns $min.
* If the number is greater than $max, returns $max.
* Otherwise, returns this number unchanged.
*
* @param BigNumber|int|string $min The minimum. Must be convertible to an instance of the class this method is called on.
* @param BigNumber|int|string $max The maximum. Must be convertible to an instance of the class this method is called on.
*
* @throws MathException If min/max are not convertible to an instance of the class this method is called on.
* @throws InvalidArgumentException If min is greater than max.
*
* @pure
*/
final public function clamp(BigNumber|int|string $min, BigNumber|int|string $max): static
{
$min = static::of($min);
$max = static::of($max);
if ($min->isGreaterThan($max)) {
throw InvalidArgumentException::minGreaterThanMax();
}
if ($this->isLessThan($min)) {
return $min;
}
if ($this->isGreaterThan($max)) {
return $max;
}
return $this;
}
/**
* Converts this number to a BigInteger.
*
* @throws RoundingNecessaryException If this number cannot be converted to a BigInteger without rounding.
*
* @pure
*/
abstract public function toBigInteger(): BigInteger;
/**
* Converts this number to a BigDecimal.
*
* @throws RoundingNecessaryException If this number cannot be converted to a BigDecimal without rounding.
*
* @pure
*/
abstract public function toBigDecimal(): BigDecimal;
/**
* Converts this number to a BigRational.
*
* @pure
*/
abstract public function toBigRational(): BigRational;
/**
* Converts this number to a BigDecimal with the given scale, using rounding if necessary.
*
* @param non-negative-int $scale The scale of the resulting `BigDecimal`. Must be non-negative.
* @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
*
* @throws InvalidArgumentException If the scale is negative.
* @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and this number cannot be converted to
* the given scale without rounding.
*
* @pure
*/
abstract public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal;
/**
* Returns the exact value of this number as a native integer.
*
* If this number cannot be converted to a native integer without losing precision, an exception is thrown.
* Note that the acceptable range for an integer depends on the platform and differs for 32-bit and 64-bit.
*
* @throws RoundingNecessaryException If this number cannot be converted to an integer without rounding.
* @throws IntegerOverflowException If this number is too large to fit in a native integer.
*
* @pure
*/
abstract public function toInt(): int;
/**
* Returns an approximation of this number as a floating-point value.
*
* Note that this method can discard information as the precision of a floating-point value
* is inherently limited.
*
* If the number is greater than the largest representable floating point number, positive infinity is returned.
* If the number is less than the smallest representable floating point number, negative infinity is returned.
* This method never returns NaN.
*
* @pure
*/
abstract public function toFloat(): float;
/**
* Returns a string representation of this number.
*
* The output of this method can be parsed by the `of()` factory method; this will yield an object equal to this
* one, but possibly of a different type if instantiated through `BigNumber::of()`.
*
* @return non-empty-string
*
* @pure
*/
abstract public function toString(): string;
/**
* @return non-empty-string
*/
#[Override]
final public function jsonSerialize(): string
{
return $this->toString();
}
/**
* @return non-empty-string
*
* @pure
*/
#[Override]
final public function __toString(): string
{
return $this->toString();
}
/**
* Overridden by subclasses to convert a BigNumber to an instance of the subclass.
*
* @throws RoundingNecessaryException If the value cannot be converted.
*
* @pure
*/
abstract protected static function from(BigNumber $number): static;
/**
* Returns the number of digits in this number, as written by toString().
*
* @pure
*/
abstract protected function digitCount(): int;
/**
* Proxy method to access BigInteger's protected constructor from sibling classes.
*
* @internal
*
* @pure
*/
final protected function newBigInteger(string $value): BigInteger
{
return new BigInteger($value);
}
/**
* Proxy method to access BigDecimal's protected constructor from sibling classes.
*
* @internal
*
* @param non-negative-int $scale
*
* @pure
*/
final protected function newBigDecimal(string $value, int $scale = 0): BigDecimal
{
return new BigDecimal($value, $scale);
}
/**
* Proxy method to access BigRational's protected constructor from sibling classes.
*
* @internal
*
* @pure
*/
final protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify): BigRational
{
return new BigRational($numerator, $denominator, $checkDenominator, $simplify);
}
/**
* @throws NumberFormatException If the format of the number is not valid.
*
* @pure
*/
private static function _of(BigNumber|int|string $value): BigNumber
{
if ($value instanceof BigNumber) {
return $value;
}
if (is_int($value)) {
return new BigInteger((string) $value);
}
return self::_parse($value, null, null);
}
/**
* Note: $allowedSyntax and $maxDigits are nullable as a performance optimization for of(): null behaves like
* `NumberSyntax::ALL` and `PHP_INT_MAX`, but skips the checks, which could never fail against those values.
*
* @param list<NumberSyntax>|null $allowedSyntax The allowed syntax features; plain integers are always accepted. Null for all.
* @param positive-int|null $maxDigits The maximum number of digits, as written and in the resulting number. Null for no limit.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
*
* @pure
*/
private static function _parse(string $value, ?array $allowedSyntax, ?int $maxDigits): BigNumber
{
if ($value === '') {
throw NumberFormatException::emptyNumber();
}
if (str_contains($value, '/')) {
// Rational number
$result = preg_match(self::PARSE_REGEXP_RATIONAL, $value, $matches, PREG_UNMATCHED_AS_NULL);
if ($result === false) {
throw PlatformException::pcreFailure();
}
if ($result === 0) {
throw NumberFormatException::invalidFormat($value);
}
if ($allowedSyntax !== null && ! in_array(NumberSyntax::Fraction, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::Fraction);
}
$sign = $matches['sign'];
$numerator = self::cleanUp($sign, $matches['numerator']);
$denominator = self::cleanUp(null, $matches['denominator']);
if ($denominator === '0') {
throw NumberFormatException::zeroDenominator();
}
// The digit count is taken as written, before trimming zeros and before simplification:
// the final count will always be less or equal.
if ($maxDigits !== null && strlen($matches['numerator']) + strlen($matches['denominator']) > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
return new BigRational(
new BigInteger($numerator),
new BigInteger($denominator),
false,
true,
);
}
// Integer or decimal number
$result = preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL);
if ($result === false) {
throw PlatformException::pcreFailure();
}
if ($result === 0) {
throw NumberFormatException::invalidFormat($value);
}
$sign = $matches['sign'];
$point = $matches['point'];
$integral = $matches['integral'];
$fractional = $matches['fractional'];
$exponent = $matches['exponent'];
if ($integral === null && $fractional === null) {
throw NumberFormatException::invalidFormat($value);
}
if ($integral === null) {
$integral = '0';
}
if ($point === null && $exponent === null) {
// Integer number.
if ($maxDigits !== null && strlen($integral) > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
$integral = self::cleanUp($sign, $integral);
return new BigInteger($integral);
}
// Decimal number.
if ($allowedSyntax !== null) {
if ($point !== null && ! in_array(NumberSyntax::DecimalPoint, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::DecimalPoint);
}
if ($exponent !== null && ! in_array(NumberSyntax::Exponent, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::Exponent);
}
}
if ($exponent === null) {
$exponent = 0;
} else {
$exponentSign = $exponent[0] === '-' ? '-' : '';
$exponent = ltrim(ltrim($exponent, '+-'), '0');
if ($exponent === '') {
$exponent = 0;
} else {
$exponent = filter_var($exponentSign . $exponent, FILTER_VALIDATE_INT);
if ($exponent === false) {
throw NumberFormatException::exponentTooLarge();
}
}
}
$fractional ??= '';
$unscaledValue = self::cleanUp($sign, $integral . $fractional);
$scale = strlen($fractional) - $exponent;
// @phpstan-ignore function.alreadyNarrowedType (may overflow to float)
if (! is_int($scale)) {
throw NumberFormatException::exponentTooLarge();
}
$unscaledDigits = strlen($unscaledValue) - (int) ($unscaledValue[0] === '-');
if ($scale < 0 && $unscaledValue !== '0') {
// The unscaled value is padded with -$scale zeros below.
$expandedDigits = $unscaledDigits - $scale;
} else {
// The fractional digits, plus at least a zero integer part.
$expandedDigits = max($unscaledDigits, $scale + 1);
}
// @phpstan-ignore function.alreadyNarrowedType (may overflow to float)
if (! is_int($expandedDigits)) {
throw NumberFormatException::tooManyDigits($maxDigits ?? PHP_INT_MAX);
}
if ($maxDigits !== null) {
// Digits as written: every digit of the input counts, including leading zeros and exponent digits.
$writtenDigits = strlen($matches['integral'] ?? '') + strlen($matches['fractional'] ?? '');
if ($matches['exponent'] !== null) {
$writtenDigits += strlen($matches['exponent']) - (int) ($matches['exponent'][0] === '-' || $matches['exponent'][0] === '+');
}
if ($expandedDigits > $maxDigits || $writtenDigits > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
}
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= str_repeat('0', Safe::neg($scale));
}
$scale = 0;
}
return new BigDecimal($unscaledValue, $scale);
}
/**
* Removes optional leading zeros and applies sign.
*
* @param '+'|'-'|null $sign The sign, optional. Null is allowed for convenience and treated as '+'.
* @param non-empty-string $number The number, validated as a string of digits.
*
* @pure
*/
private static function cleanUp(?string $sign, string $number): string
{
$number = ltrim($number, '0');
if ($number === '') {
return '0';
}
return $sign === '-' ? '-' . $number : $number;
}
/**
* Adds two BigNumber instances in the correct order to avoid a RoundingNecessaryException.
*
* @pure
*/
private static function add(BigNumber $a, BigNumber $b): BigNumber
{
if ($a instanceof BigRational) {
return $a->plus($b);
}
if ($b instanceof BigRational) {
return $b->plus($a);
}
if ($a instanceof BigDecimal) {
return $a->plus($b);
}
if ($b instanceof BigDecimal) {
return $b->plus($a);
}
return $a->plus($b);
}
}

605
vendor/brick/math/src/BigRational.php vendored Normal file
View file

@ -0,0 +1,605 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\DivisionByZeroException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Math\Internal\DecimalHelper;
use Brick\Math\Internal\Safe;
use LogicException;
use Override;
use function max;
use function min;
use function strlen;
use function substr;
/**
* An arbitrarily large rational number.
*
* This class is immutable.
*
* Fractions are automatically simplified to lowest terms. For example, `2/4` becomes `1/2`.
* The denominator is always strictly positive; the sign is carried by the numerator.
*/
final readonly class BigRational extends BigNumber
{
/**
* The numerator.
*/
private BigInteger $numerator;
/**
* The denominator. Always strictly positive.
*/
private BigInteger $denominator;
/**
* Protected constructor. Use a factory method to obtain an instance.
*
* @param BigInteger $numerator The numerator.
* @param BigInteger $denominator The denominator.
* @param bool $checkDenominator Whether to check the denominator for negative and zero.
* @param bool $simplify Whether to simplify the fraction to lowest terms.
*
* @throws DivisionByZeroException If the denominator is zero.
*
* @pure
*/
protected function __construct(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify)
{
if ($checkDenominator) {
if ($denominator->isZero()) {
throw DivisionByZeroException::zeroDenominator();
}
if ($denominator->isNegative()) {
$numerator = $numerator->negated();
$denominator = $denominator->negated();
}
}
if ($simplify) {
$gcd = $numerator->gcd($denominator);
$numerator = $numerator->quotient($gcd);
$denominator = $denominator->quotient($gcd);
}
$this->numerator = $numerator;
$this->denominator = $denominator;
}
/**
* Creates a BigRational out of a numerator and a denominator.
*
* If the denominator is negative, the signs of both the numerator and the denominator
* will be inverted to ensure that the denominator is always positive.
*
* @param BigNumber|int|string $numerator The numerator. Must be convertible to a BigInteger.
* @param BigNumber|int|string $denominator The denominator. Must be convertible to a BigInteger.
*
* @throws MathException If an argument is not valid, or is not convertible to a BigInteger.
* @throws DivisionByZeroException If the denominator is zero.
*
* @pure
*/
public static function ofFraction(
BigNumber|int|string $numerator,
BigNumber|int|string $denominator,
): BigRational {
$numerator = BigInteger::of($numerator);
$denominator = BigInteger::of($denominator);
return new BigRational($numerator, $denominator, true, true);
}
/**
* Returns a BigRational representing zero.
*
* @pure
*/
public static function zero(): BigRational
{
/** @var BigRational|null $zero */
static $zero;
if ($zero === null) {
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false, false);
}
return $zero;
}
/**
* Returns a BigRational representing one.
*
* @pure
*/
public static function one(): BigRational
{
/** @var BigRational|null $one */
static $one;
if ($one === null) {
$one = new BigRational(BigInteger::one(), BigInteger::one(), false, false);
}
return $one;
}
/**
* Returns a BigRational representing ten.
*
* @pure
*/
public static function ten(): BigRational
{
/** @var BigRational|null $ten */
static $ten;
if ($ten === null) {
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false, false);
}
return $ten;
}
/**
* Returns the numerator of this rational number.
*
* @pure
*/
public function getNumerator(): BigInteger
{
return $this->numerator;
}
/**
* Returns the denominator of this rational number.
*
* The denominator is always strictly positive.
*
* @pure
*/
public function getDenominator(): BigInteger
{
return $this->denominator;
}
/**
* Returns the integral part of this rational number.
*
* Examples:
*
* - `7/3` returns `2` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-2` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
public function getIntegralPart(): BigInteger
{
return $this->numerator->quotient($this->denominator);
}
/**
* Returns the fractional part of this rational number.
*
* Examples:
*
* - `7/3` returns `1/3` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-1/3` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
public function getFractionalPart(): BigRational
{
return new BigRational($this->numerator->remainder($this->denominator), $this->denominator, false, false);
}
/**
* Returns the sum of this number and the given one.
*
* @param BigNumber|int|string $that The number to add.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function plus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that;
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the difference of this number and the given one.
*
* @param BigNumber|int|string $that The number to subtract.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function minus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that->negated();
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->minus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the product of this number and the given one.
*
* @param BigNumber|int|string $that The multiplier.
*
* @throws MathException If the multiplier is not valid.
*
* @pure
*/
public function multipliedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero() || $this->isZero()) {
return BigRational::zero();
}
$numerator = $this->numerator->multipliedBy($that->numerator);
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the result of the division of this number by the given one.
*
* @param BigNumber|int|string $that The divisor.
*
* @throws MathException If the divisor is not valid.
* @throws DivisionByZeroException If the divisor is zero.
*
* @pure
*/
public function dividedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$denominator = $this->denominator->multipliedBy($that->numerator);
return new BigRational($numerator, $denominator, true, true);
}
/**
* Returns this number exponentiated to the given value.
*
* Unlike BigInteger and BigDecimal, BigRational supports negative exponents:
* the result is the reciprocal raised to the absolute value of the exponent.
*
* @throws DivisionByZeroException If the exponent is negative and this number is zero.
*
* @pure
*/
public function power(int $exponent): BigRational
{
if ($exponent === 0) {
return BigRational::one();
}
if ($exponent === 1) {
return $this;
}
if ($exponent < 0) {
if ($this->isZero()) {
throw DivisionByZeroException::zeroToNegativePower();
}
return $this->reciprocal()->power(Safe::neg($exponent));
}
return new BigRational(
$this->numerator->power($exponent),
$this->denominator->power($exponent),
false,
false,
);
}
/**
* Returns the reciprocal of this BigRational.
*
* The reciprocal has the numerator and denominator swapped.
*
* @throws DivisionByZeroException If this number is zero.
*
* @pure
*/
public function reciprocal(): BigRational
{
if ($this->isZero()) {
throw DivisionByZeroException::reciprocalOfZero();
}
return new BigRational($this->denominator, $this->numerator, true, false);
}
#[Override]
public function negated(): static
{
return new BigRational($this->numerator->negated(), $this->denominator, false, false);
}
#[Override]
public function compareTo(BigNumber|int|string $that): int
{
$that = BigRational::of($that);
if ($this->denominator->isEqualTo($that->denominator)) {
return $this->numerator->compareTo($that->numerator);
}
return $this->numerator
->multipliedBy($that->denominator)
->compareTo($that->numerator->multipliedBy($this->denominator));
}
#[Override]
public function getSign(): int
{
return $this->numerator->getSign();
}
#[Override]
public function toBigInteger(): BigInteger
{
if ($this->denominator->isEqualTo(1)) {
return $this->numerator;
}
throw RoundingNecessaryException::rationalNotConvertibleToInteger();
}
#[Override]
public function toBigDecimal(): BigDecimal
{
$scale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($scale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale)->strippedOfTrailingZeros();
}
#[Override]
public function toBigRational(): BigRational
{
return $this;
}
#[Override]
public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
{
if ($scale < 0) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::negativeScale();
}
if ($roundingMode === RoundingMode::Unnecessary) {
$requiredScale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($requiredScale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
if ($requiredScale > $scale) {
throw RoundingNecessaryException::rationalScaleTooSmall();
}
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode);
}
#[Override]
public function toInt(): int
{
return $this->toBigInteger()->toInt();
}
#[Override]
public function toFloat(): float
{
if ($this->denominator->isEqualTo(1)) {
return $this->numerator->toFloat();
}
// Avoid $this->numerator->toFloat() / $this->denominator->toFloat(): converting both operands to float first
// adds an extra rounding step before the division and can change the final float. Instead, divide in decimal
// first and convert the resulting decimal approximation to float once.
// We need ~17 significant digits for double precision (we use 20 for some margin). Since $scale controls
// decimal places (not significant digits), we subtract the estimated order of magnitude so that large results
// use fewer decimal places and small results use more (to look past leading zeros). Clamped to [0, 350] as
// doubles range from e-324 to e308 (350 ≈ 324 + 20 significant digits + margin).
$magnitude = strlen($this->numerator->abs()->toString()) - strlen($this->denominator->toString());
$scale = min(350, max(0, 20 - $magnitude));
$result = $this->numerator
->toBigDecimal()
->dividedBy($this->denominator, $scale, RoundingMode::HalfEven)
->toFloat();
// Preserve the sign when the decimal approximation underflows to zero.
if ($result === 0.0 && $this->numerator->isNegative()) {
return -0.0;
}
return $result;
}
#[Override]
public function toString(): string
{
$numerator = $this->numerator->toString();
$denominator = $this->denominator->toString();
if ($denominator === '1') {
return $numerator;
}
return $numerator . '/' . $denominator;
}
/**
* Returns the decimal representation of this rational number, with repeating decimals in parentheses.
*
* WARNING: This method is unbounded.
* The length of the repeating decimal period can be as large as `denominator - 1`.
* For fractions with large denominators, this method can use excessive memory and CPU time.
* For example, `1/100019` has a repeating period of 100,018 digits.
*
* Examples:
*
* - `10/3` returns `3.(3)`
* - `171/70` returns `2.4(428571)`
* - `1/2` returns `0.5`
*
* @return non-empty-string
*
* @pure
*/
public function toRepeatingDecimalString(): string
{
if ($this->isZero()) {
return '0';
}
$sign = $this->numerator->isNegative() ? '-' : '';
$numerator = $this->numerator->abs();
$denominator = $this->denominator;
$integral = $numerator->quotient($denominator);
$remainder = $numerator->remainder($denominator);
$integralString = $integral->toString();
if ($remainder->isZero()) {
return $sign . $integralString;
}
$digits = '';
$remainderPositions = [];
$index = 0;
while (! $remainder->isZero()) {
$remainderString = $remainder->toString();
if (isset($remainderPositions[$remainderString])) {
$repeatIndex = $remainderPositions[$remainderString];
$nonRepeating = substr($digits, 0, $repeatIndex);
$repeating = substr($digits, $repeatIndex);
return $sign . $integralString . '.' . $nonRepeating . '(' . $repeating . ')';
}
$remainderPositions[$remainderString] = $index;
$remainder = $remainder->multipliedBy(10);
$digits .= $remainder->quotient($denominator)->toString();
$remainder = $remainder->remainder($denominator);
$index++;
}
return $sign . $integralString . '.' . $digits;
}
/**
* This method is required for serializing the object and SHOULD NOT be accessed directly.
*
* @internal
*
* @return array{numerator: BigInteger, denominator: BigInteger}
*/
public function __serialize(): array
{
return ['numerator' => $this->numerator, 'denominator' => $this->denominator];
}
/**
* This method is only here to allow unserializing the object and cannot be accessed directly.
*
* @internal
*
* @param array{numerator: BigInteger, denominator: BigInteger} $data
*
* @throws LogicException
*/
public function __unserialize(array $data): void
{
if (isset($this->numerator)) {
throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
}
$this->numerator = $data['numerator'];
$this->denominator = $data['denominator'];
}
#[Override]
protected static function from(BigNumber $number): static
{
return $number->toBigRational();
}
#[Override]
protected function digitCount(): int
{
$count = $this->numerator->digitCount();
// Mirrors toString(), which does not write a denominator of 1.
if ($this->denominator->toString() === '1') {
return $count;
}
return $count + $this->denominator->digitCount();
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a division by zero occurs.
*/
final class DivisionByZeroException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function divisionByZero(): self
{
return new self('Division by zero.');
}
/**
* @internal
*
* @pure
*/
public static function zeroModulus(): self
{
return new self('The modulus must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function zeroDenominator(): self
{
return new self('The denominator of a rational number must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function reciprocalOfZero(): self
{
return new self('The reciprocal of zero is undefined.');
}
/**
* @internal
*
* @pure
*/
public static function zeroToNegativePower(): self
{
return new self('Cannot raise zero to a negative power.');
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Brick\Math\BigInteger;
use RuntimeException;
use function sprintf;
use const PHP_INT_MAX;
use const PHP_INT_MIN;
/**
* Exception thrown when a native integer overflow occurs.
*/
final class IntegerOverflowException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function integerOutOfRange(BigInteger $value): self
{
$message = '%s is out of range [%d, %d] and cannot be represented as an integer.';
return new self(sprintf($message, $value->toString(), PHP_INT_MIN, PHP_INT_MAX));
}
/**
* @internal
*
* @pure
*/
public static function nativeIntegerOverflow(string $expression): self
{
return new self(sprintf(
'Cannot compute %s because the result is outside the native integer range [%d, %d].',
$expression,
PHP_INT_MIN,
PHP_INT_MAX,
));
}
}

View file

@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use function sprintf;
/**
* Exception thrown when an invalid argument is provided.
*/
final class InvalidArgumentException extends \InvalidArgumentException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function baseOutOfRange(int $base): self
{
return new self(sprintf('Base %d is out of range [2, 36].', $base));
}
/**
* @internal
*
* @pure
*/
public static function negativeScale(): self
{
return new self('The scale must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitIndex(): self
{
return new self('The bit index must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitCount(): self
{
return new self('The bit count must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function alphabetTooShort(): self
{
return new self('The alphabet must contain at least 2 characters.');
}
/**
* @internal
*
* @pure
*/
public static function duplicateCharsInAlphabet(): self
{
return new self('The alphabet must not contain duplicate characters.');
}
/**
* @internal
*
* @pure
*/
public static function minGreaterThanMax(): self
{
return new self('The minimum value must be less than or equal to the maximum value.');
}
/**
* @internal
*
* @pure
*/
public static function cannotConvertFloat(string $type): self
{
return new self(sprintf('Cannot convert %s to a BigDecimal.', $type));
}
/**
* @internal
*
* @pure
*/
public static function negativeExponent(): self
{
return new self('The exponent must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeModulus(): self
{
return new self('The modulus must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function nonPositiveNthRootDegree(): self
{
return new self('The degree of an nth root must be a positive integer.');
}
/**
* @internal
*
* @pure
*/
public static function nonPositiveMaxDigits(): self
{
return new self('The maximum number of digits must be a positive integer.');
}
/**
* @internal
*
* @pure
*/
public static function invalidAllowedSyntax(): self
{
return new self('The allowed syntax must be a list of NumberSyntax cases.');
}
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Throwable;
/**
* Base interface for all math exceptions.
*/
interface MathException extends Throwable
{
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to perform an unsupported operation, such as a square root, on a negative number.
*/
final class NegativeNumberException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function squareRootOfNegativeNumber(): self
{
return new self('Cannot calculate the square root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function nthRootOfNegativeNumber(): self
{
return new self('Cannot take an even nth root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function toArbitraryBaseOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to an arbitrary base.');
}
/**
* @internal
*
* @pure
*/
public static function unsignedBytesOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to a byte string in unsigned mode.');
}
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to compute a modular inverse that does not exist.
*/
final class NoInverseException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function noModularInverse(): self
{
return new self('This number has no multiplicative inverse modulo the given modulus (they are not coprime).');
}
}

View file

@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Brick\Math\NumberSyntax;
use RuntimeException;
use function ord;
use function sprintf;
use function strlen;
use function substr;
/**
* Exception thrown when attempting to create a number from a string with an invalid format.
*/
final class NumberFormatException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function invalidFormat(string $value): self
{
return new self(sprintf(
'Value "%s" does not represent a valid number.',
self::truncateAndEscape($value),
));
}
/**
* @internal
*
* @param string $char The failing character.
*
* @pure
*/
public static function charNotInAlphabet(string $char): self
{
return new self(sprintf(
'Character "%s" is not valid in the given alphabet.',
self::escapeChar($char),
));
}
/**
* @internal
*
* @pure
*/
public static function charNotValidInBase(string $char, int $base): self
{
return new self(sprintf(
'Character "%s" is not valid in base %d.',
self::escapeChar($char),
$base,
));
}
/**
* @internal
*
* @pure
*/
public static function emptyNumber(): self
{
return new self('The number must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function emptyByteString(): self
{
return new self('The byte string must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function exponentTooLarge(): self
{
return new self('The exponent is too large to be represented as an integer.');
}
/**
* @internal
*
* @pure
*/
public static function tooManyDigits(int $maxDigits): self
{
return new self(sprintf(
'The number exceeds the maximum number of %d digits.',
$maxDigits,
));
}
/**
* @internal
*
* @pure
*/
public static function syntaxNotAllowed(NumberSyntax $syntax): self
{
return new self(sprintf('The %s syntax is not allowed.', match ($syntax) {
NumberSyntax::DecimalPoint => 'decimal point',
NumberSyntax::Exponent => 'exponent',
NumberSyntax::Fraction => 'fraction',
}));
}
/**
* @internal
*
* @pure
*/
public static function zeroDenominator(): self
{
return new self('The denominator of a rational number must not be zero.');
}
/**
* @pure
*/
private static function truncateAndEscape(string $value): string
{
if (strlen($value) > 40) {
$value = substr($value, 0, 40) . '...';
}
$escaped = '';
$length = strlen($value);
for ($i = 0; $i < $length; $i++) {
$escaped .= self::escapeChar($value[$i]);
}
return $escaped;
}
/**
* @pure
*/
private static function escapeChar(string $char): string
{
$ord = ord($char);
return match (true) {
$char === "\t" => '\t',
$char === "\n" => '\n',
$char === "\r" => '\r',
$char === '\\' => '\\\\',
$char === '"' => '\"',
$ord < 32 || $ord > 126 => sprintf('\x%02X', $ord),
default => $char,
};
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use function preg_last_error_msg;
use function sprintf;
use const PHP_INT_SIZE;
/**
* Exception thrown when the current PHP platform does not support a required feature.
*/
final class PlatformException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*
* @codeCoverageIgnore
*/
public static function unsupportedFloatFormat(): self
{
return new self('Unsupported float format: expected IEEE-754 double.');
}
/**
* @internal
*
* @pure
*
* @codeCoverageIgnore
*/
public static function unsupportedIntSize(): self
{
return new self(sprintf('Unsupported integer size: %d bytes, expected 4 or 8.', PHP_INT_SIZE));
}
/**
* @internal
*
* @pure
*/
public static function pcreFailure(): self
{
return new self(sprintf(
'PCRE regular expression matching failed: %s. Check the pcre.* ini settings.',
preg_last_error_msg(),
));
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use Throwable;
use function get_debug_type;
use function sprintf;
/**
* Exception thrown when random byte generation fails.
*/
final class RandomSourceException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message, ?Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
/**
* @internal
*
* @pure
*/
public static function randomSourceFailure(Throwable $previous): self
{
return new self('Random byte generation failed.', $previous);
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesType(mixed $value): self
{
return new self(sprintf(
'The random bytes generator must return a string, got %s.',
get_debug_type($value),
));
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesLength(int $expectedLength, int $actualLength): self
{
return new self(sprintf(
'The random bytes generator returned %d byte(s), expected %d.',
$actualLength,
$expectedLength,
));
}
}

View file

@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a number cannot be represented at the requested scale without rounding.
*/
final class RoundingNecessaryException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function decimalScaleTooSmall(): self
{
return new self('This decimal number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalScaleTooSmall(): self
{
return new self('This rational number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerDivisionNotExact(): self
{
return new self('The division has a non-zero remainder and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionNotExact(): self
{
return new self('The division yields a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionScaleTooSmall(): self
{
return new self('The division result is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootScaleTooSmall(): self
{
return new self('The square root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootScaleTooSmall(): self
{
return new self('The nth root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNotConvertibleToInteger(): self
{
return new self('This decimal number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToInteger(): self
{
return new self('This rational number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToDecimal(): self
{
return new self('This rational number has a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
}

View file

@ -0,0 +1,723 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\RoundingMode;
use function chr;
use function intdiv;
use function ltrim;
use function ord;
use function str_repeat;
use function strlen;
use function strpos;
use function strrev;
use function strtolower;
use function substr;
/**
* Performs basic operations on arbitrary size integers.
*
* Unless otherwise specified, all parameters must be validated as non-empty strings of digits,
* without leading zero, and with an optional leading minus sign if the number is not zero.
*
* Any other parameter format will lead to undefined behaviour.
* All methods must return strings respecting this format, unless specified otherwise.
*
* @internal
*/
abstract readonly class Calculator
{
/**
* The alphabet for converting from and to base 2 to 36, lowercase.
*/
public const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
/**
* Returns the absolute value of a number.
*
* @pure
*/
final public function abs(string $n): string
{
return ($n[0] === '-') ? substr($n, 1) : $n;
}
/**
* Negates a number.
*
* @pure
*/
final public function neg(string $n): string
{
if ($n === '0') {
return '0';
}
if ($n[0] === '-') {
return substr($n, 1);
}
return '-' . $n;
}
/**
* Compares two numbers.
*
* Returns -1 if the first number is less than, 0 if equal to, 1 if greater than the second number.
*
* @return -1|0|1
*
* @pure
*/
final public function cmp(string $a, string $b): int
{
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
if ($aNeg && ! $bNeg) {
return -1;
}
if ($bNeg && ! $aNeg) {
return 1;
}
$aLen = strlen($aDig);
$bLen = strlen($bDig);
if ($aLen < $bLen) {
$result = -1;
} elseif ($aLen > $bLen) {
$result = 1;
} else {
$result = $aDig <=> $bDig;
}
return $aNeg ? -$result : $result;
}
/**
* Adds two numbers.
*
* @pure
*/
abstract public function add(string $a, string $b): string;
/**
* Subtracts two numbers.
*
* @pure
*/
abstract public function sub(string $a, string $b): string;
/**
* Multiplies two numbers.
*
* @pure
*/
abstract public function mul(string $a, string $b): string;
/**
* Returns the quotient of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return string The quotient.
*
* @pure
*/
abstract public function divQ(string $a, string $b): string;
/**
* Returns the remainder of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return string The remainder.
*
* @pure
*/
abstract public function divR(string $a, string $b): string;
/**
* Returns the quotient and remainder of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return array{string, string} An array containing the quotient and remainder.
*
* @pure
*/
abstract public function divQR(string $a, string $b): array;
/**
* Exponentiates a number.
*
* @param string $a The base number.
* @param int $e The exponent, validated as a non-negative integer.
*
* @return string The power.
*
* @pure
*/
abstract public function pow(string $a, int $e): string;
/**
* @param string $b The modulus; must not be zero.
*
* @pure
*/
public function mod(string $a, string $b): string
{
return $this->divR($this->add($this->divR($a, $b), $b), $b);
}
/**
* Returns the modular multiplicative inverse of $x modulo $m.
*
* If $x has no multiplicative inverse mod m, this method must return null.
*
* This method can be overridden by the concrete implementation if the underlying library has built-in support.
*
* @param string $m The modulus; must not be negative or zero.
*
* @pure
*/
public function modInverse(string $x, string $m): ?string
{
if ($m === '1') {
return '0';
}
$modVal = $x;
if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) {
$modVal = $this->mod($x, $m);
}
[$g, $x] = $this->gcdExtended($modVal, $m);
if ($g !== '1') {
return null;
}
return $this->mod($this->add($this->mod($x, $m), $m), $m);
}
/**
* Raises a number into power with modulo.
*
* @param string $base The base number.
* @param string $exp The exponent; must be positive or zero.
* @param string $mod The modulus; must be strictly positive.
*
* @pure
*/
abstract public function modPow(string $base, string $exp, string $mod): string;
/**
* Returns the greatest common divisor of the two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for GCD calculations.
*
* @return string The GCD, always positive, or zero if both arguments are zero.
*
* @pure
*/
public function gcd(string $a, string $b): string
{
while ($b !== '0') {
[$a, $b] = [$b, $this->divR($a, $b)];
}
return $this->abs($a);
}
/**
* Returns the least common multiple of the two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for LCM calculations.
*
* @return string The LCM, always positive, or zero if at least one argument is zero.
*
* @pure
*/
public function lcm(string $a, string $b): string
{
if ($a === '0' || $b === '0') {
return '0';
}
return $this->divQ($this->abs($this->mul($a, $b)), $this->gcd($a, $b));
}
/**
* Returns the square root of the given number, rounded down.
*
* The result is the largest x such that x² ≤ n.
* The input MUST NOT be negative.
*
* @pure
*/
abstract public function sqrt(string $n): string;
/**
* Returns the integer nth root of the given number, truncated toward zero.
*
* If $n is non-negative, the result is the largest x such that x^$k ≤ $n (floor).
* If $n is negative, $k MUST be odd, and the result is the negation of the floor root of |$n|
* (i.e., truncation toward zero: the smallest x such that x^$k ≥ $n).
*
* The caller MUST guarantee that $k ≥ 1 and that $n is non-negative when $k is even.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for nth root calculations.
*
* @param string $n The number. May be negative only when $k is odd.
* @param int $k The root degree. Must be strictly positive.
*
* @pure
*/
public function nthRoot(string $n, int $k): string
{
if ($n === '0') {
return '0';
}
$negative = ($n[0] === '-');
$m = $negative ? substr($n, 1) : $n;
if ($m === '1') {
return $negative ? '-1' : '1';
}
// Initial overshoot: 10^ceil(strlen(m)/k) is strictly greater than the true root.
// Newton-Raphson requires starting above the true root to converge monotonically down.
$x = '1' . str_repeat('0', intdiv(strlen($m) - 1, $k) + 1);
$kStr = (string) $k;
$kMinusOneStr = (string) ($k - 1);
// Newton-Raphson recurrence for integer nth root:
// x_{i+1} = floor(((k-1) * x_i + floor(m / x_i^{k-1})) / k)
for (; ;) {
$nx = $this->divQ(
$this->add(
$this->mul($kMinusOneStr, $x),
$this->divQ($m, $this->pow($x, $k - 1)),
),
$kStr,
);
if ($this->cmp($nx, $x) >= 0) {
break;
}
$x = $nx;
}
return $negative ? $this->neg($x) : $x;
}
/**
* Converts a number from an arbitrary base.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for base conversion.
*
* @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
* @param int $base The base of the number, validated from 2 to 36.
*
* @return string The converted number, following the Calculator conventions.
*
* @pure
*/
public function fromBase(string $number, int $base): string
{
return $this->fromArbitraryBase(strtolower($number), self::ALPHABET, $base);
}
/**
* Converts a number to an arbitrary base.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for base conversion.
*
* @param string $number The number to convert, following the Calculator conventions.
* @param int $base The base to convert to, validated from 2 to 36.
*
* @return string The converted number, lowercase.
*
* @pure
*/
public function toBase(string $number, int $base): string
{
$negative = ($number[0] === '-');
if ($negative) {
$number = substr($number, 1);
}
$number = $this->toArbitraryBase($number, self::ALPHABET, $base);
if ($negative) {
return '-' . $number;
}
return $number;
}
/**
* Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
*
* @param string $number The number to convert, validated as a non-empty string,
* containing only chars in the given alphabet/base.
* @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
* @param int $base The base of the number, validated from 2 to alphabet length.
*
* @return string The number in base 10, following the Calculator conventions.
*
* @pure
*/
final public function fromArbitraryBase(string $number, string $alphabet, int $base): string
{
// remove leading "zeros"
$number = ltrim($number, $alphabet[0]);
if ($number === '') {
return '0';
}
// optimize for "one"
if ($number === $alphabet[1]) {
return '1';
}
$result = '0';
$power = '1';
$base = (string) $base;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$index = strpos($alphabet, $number[$i]);
if ($index !== 0) {
$result = $this->add(
$result,
($index === 1) ? $power : $this->mul($power, (string) $index),
);
}
if ($i !== 0) {
$power = $this->mul($power, $base);
}
}
return $result;
}
/**
* Converts a non-negative number to an arbitrary base using a custom alphabet.
*
* @param string $number The number to convert, positive or zero, following the Calculator conventions.
* @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
* @param int $base The base to convert to, validated from 2 to alphabet length.
*
* @return string The converted number in the given alphabet.
*
* @pure
*/
final public function toArbitraryBase(string $number, string $alphabet, int $base): string
{
if ($number === '0') {
return $alphabet[0];
}
$base = (string) $base;
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, $base);
$remainder = (int) $remainder;
$result .= $alphabet[$remainder];
}
return strrev($result);
}
/**
* Performs a rounded division.
*
* When the remainder of the division is not zero, rounding is performed according to the rounding mode provided,
* unless RoundingMode::Unnecessary is used, in which case the method returns null.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
* @param RoundingMode $roundingMode The rounding mode.
*
* @pure
*/
final public function divRound(string $a, string $b, RoundingMode $roundingMode): ?string
{
[$quotient, $remainder] = $this->divQR($a, $b);
$hasDiscardedFraction = ($remainder !== '0');
$isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-');
$discardedFractionSign = function () use ($remainder, $b): int {
$r = $this->abs($this->mul($remainder, '2'));
$b = $this->abs($b);
return $this->cmp($r, $b);
};
$lastDigitIsEven = (int) $quotient[-1] % 2 === 0;
$increment = match ($roundingMode) {
RoundingMode::Unnecessary => $hasDiscardedFraction ? null : false,
RoundingMode::Up => $hasDiscardedFraction,
RoundingMode::Down => false,
RoundingMode::Ceiling => $hasDiscardedFraction && $isPositiveOrZero,
RoundingMode::Floor => $hasDiscardedFraction && ! $isPositiveOrZero,
RoundingMode::HalfUp => $discardedFractionSign() >= 0,
RoundingMode::HalfDown => $discardedFractionSign() > 0,
RoundingMode::HalfCeiling => $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0,
RoundingMode::HalfFloor => $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0,
RoundingMode::HalfEven => $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0,
RoundingMode::HalfOdd => $lastDigitIsEven ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0,
};
if ($increment === null) {
return null;
}
if ($increment) {
return $isPositiveOrZero
? $this->add($quotient, '1')
: $this->sub($quotient, '1');
}
return $quotient;
}
/**
* Calculates bitwise AND of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function and(string $a, string $b): string
{
return $this->bitwise('and', $a, $b);
}
/**
* Calculates bitwise OR of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function or(string $a, string $b): string
{
return $this->bitwise('or', $a, $b);
}
/**
* Calculates bitwise XOR of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function xor(string $a, string $b): string
{
return $this->bitwise('xor', $a, $b);
}
/**
* Extracts the sign & digits of the operands.
*
* @return array{bool, bool, string, string} Whether $a and $b are negative, followed by their digits.
*
* @pure
*/
final protected function init(string $a, string $b): array
{
return [
$aNeg = ($a[0] === '-'),
$bNeg = ($b[0] === '-'),
$aNeg ? substr($a, 1) : $a,
$bNeg ? substr($b, 1) : $b,
];
}
/**
* @param string $a Must be non-negative.
* @param string $b Must be non-negative.
*
* @return array{string, string} GCD, X
*
* @pure
*/
private function gcdExtended(string $a, string $b): array
{
// Iterative extended Euclidean algorithm; recursion would exhaust memory on large inputs.
[$r0, $r1] = [$a, $b];
[$x0, $x1] = ['1', '0'];
while ($r1 !== '0') {
[$q, $r] = $this->divQR($r0, $r1);
[$r0, $r1] = [$r1, $r];
[$x0, $x1] = [$x1, $this->sub($x0, $this->mul($q, $x1))];
}
return [$r0, $x0];
}
/**
* Performs a bitwise operation on a decimal number.
*
* @param 'and'|'or'|'xor' $operator The operator to use.
* @param string $a The left operand.
* @param string $b The right operand.
*
* @pure
*/
private function bitwise(string $operator, string $a, string $b): string
{
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$aBin = $this->toBinary($aDig);
$bBin = $this->toBinary($bDig);
$aLen = strlen($aBin);
$bLen = strlen($bBin);
if ($aLen > $bLen) {
$bBin = str_repeat("\x00", $aLen - $bLen) . $bBin;
} elseif ($bLen > $aLen) {
$aBin = str_repeat("\x00", $bLen - $aLen) . $aBin;
}
if ($aNeg) {
$aBin = $this->twosComplement($aBin);
}
if ($bNeg) {
$bBin = $this->twosComplement($bBin);
}
$value = match ($operator) {
'and' => $aBin & $bBin,
'or' => $aBin | $bBin,
'xor' => $aBin ^ $bBin,
};
$negative = match ($operator) {
'and' => $aNeg and $bNeg,
'or' => $aNeg or $bNeg,
'xor' => $aNeg xor $bNeg,
};
if ($negative) {
$value = $this->twosComplement($value);
}
$result = $this->toDecimal($value);
return $negative ? $this->neg($result) : $result;
}
/**
* @param string $number A positive, binary number.
*
* @pure
*/
private function twosComplement(string $number): string
{
$xor = str_repeat("\xff", strlen($number));
$number ^= $xor;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$byte = ord($number[$i]);
if (++$byte !== 256) {
$number[$i] = chr($byte); // @phpstan-ignore argument.type
break;
}
$number[$i] = "\x00";
if ($i === 0) {
$number = "\x01" . $number;
}
}
return $number;
}
/**
* Converts a decimal number to a binary string.
*
* @param string $number The number to convert, positive or zero, only digits.
*
* @pure
*/
private function toBinary(string $number): string
{
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, '256');
$result .= chr((int) $remainder); // @phpstan-ignore argument.type
}
return strrev($result);
}
/**
* Returns the positive decimal representation of a binary number.
*
* @param string $bytes The bytes representing the number.
*
* @pure
*/
private function toDecimal(string $bytes): string
{
$result = '0';
$power = '1';
for ($i = strlen($bytes) - 1; $i >= 0; $i--) {
$index = ord($bytes[$i]);
if ($index !== 0) {
$result = $this->add(
$result,
($index === 1) ? $power : $this->mul($power, (string) $index),
);
}
if ($i !== 0) {
$power = $this->mul($power, '256');
}
}
return $result;
}
}

View file

@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Internal\Calculator;
use Override;
use function bcadd;
use function bcdiv;
use function bcmod;
use function bcmul;
use function bcpow;
use function bcpowmod;
use function bcsqrt;
use function bcsub;
/**
* Calculator implementation built around the bcmath library.
*
* @internal
*/
final readonly class BcMathCalculator extends Calculator
{
#[Override]
public function add(string $a, string $b): string
{
return bcadd($a, $b, 0);
}
#[Override]
public function sub(string $a, string $b): string
{
return bcsub($a, $b, 0);
}
#[Override]
public function mul(string $a, string $b): string
{
return bcmul($a, $b, 0);
}
#[Override]
public function divQ(string $a, string $b): string
{
return bcdiv($a, $b, 0);
}
#[Override]
public function divR(string $a, string $b): string
{
return bcmod($a, $b, 0);
}
#[Override]
public function divQR(string $a, string $b): array
{
$q = bcdiv($a, $b, 0);
$r = bcmod($a, $b, 0);
return [$q, $r];
}
#[Override]
public function pow(string $a, int $e): string
{
if ($e === 0) {
return '1';
}
// bcpow() allocates memory proportional to the exponent even when the base is trivial,
// exhausting memory on 32-bit builds at large exponents.
if ($a === '0' || $a === '1') {
return $a;
}
if ($a === '-1') {
return $e % 2 === 0 ? '1' : '-1';
}
return bcpow($a, (string) $e, 0);
}
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
// normalize to Euclidean representative so modPow() stays consistent with mod()
$base = $this->mod($base, $mod);
return bcpowmod($base, $exp, $mod, 0);
}
#[Override]
public function sqrt(string $n): string
{
return bcsqrt($n, 0);
}
}

View file

@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Internal\Calculator;
use GMP;
use Override;
use function gmp_add;
use function gmp_and;
use function gmp_div_q;
use function gmp_div_qr;
use function gmp_div_r;
use function gmp_gcd;
use function gmp_init;
use function gmp_invert;
use function gmp_lcm;
use function gmp_mul;
use function gmp_or;
use function gmp_pow;
use function gmp_powm;
use function gmp_root;
use function gmp_sqrt;
use function gmp_strval;
use function gmp_sub;
use function gmp_xor;
use function substr;
/**
* Calculator implementation built around the GMP library.
*
* @internal
*/
final readonly class GmpCalculator extends Calculator
{
#[Override]
public function add(string $a, string $b): string
{
return gmp_strval(gmp_add($a, $b));
}
#[Override]
public function sub(string $a, string $b): string
{
return gmp_strval(gmp_sub($a, $b));
}
#[Override]
public function mul(string $a, string $b): string
{
return gmp_strval(gmp_mul($a, $b));
}
#[Override]
public function divQ(string $a, string $b): string
{
return gmp_strval(gmp_div_q($a, $b));
}
#[Override]
public function divR(string $a, string $b): string
{
return gmp_strval(gmp_div_r($a, $b));
}
#[Override]
public function divQR(string $a, string $b): array
{
[$q, $r] = gmp_div_qr($a, $b);
/**
* @var GMP $q
* @var GMP $r
*/
return [
gmp_strval($q),
gmp_strval($r),
];
}
#[Override]
public function pow(string $a, int $e): string
{
return gmp_strval(gmp_pow($a, $e));
}
#[Override]
public function modInverse(string $x, string $m): ?string
{
$result = gmp_invert($x, $m);
if ($result === false) {
return null;
}
return gmp_strval($result);
}
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
return gmp_strval(gmp_powm($base, $exp, $mod));
}
#[Override]
public function gcd(string $a, string $b): string
{
return gmp_strval(gmp_gcd($a, $b));
}
#[Override]
public function lcm(string $a, string $b): string
{
return gmp_strval(gmp_lcm($a, $b));
}
#[Override]
public function fromBase(string $number, int $base): string
{
return gmp_strval(gmp_init($number, $base));
}
#[Override]
public function toBase(string $number, int $base): string
{
return gmp_strval($number, $base);
}
#[Override]
public function and(string $a, string $b): string
{
return gmp_strval(gmp_and($a, $b));
}
#[Override]
public function or(string $a, string $b): string
{
return gmp_strval(gmp_or($a, $b));
}
#[Override]
public function xor(string $a, string $b): string
{
return gmp_strval(gmp_xor($a, $b));
}
#[Override]
public function sqrt(string $n): string
{
return gmp_strval(gmp_sqrt($n));
}
#[Override]
public function nthRoot(string $n, int $k): string
{
// Delegate on the absolute value and re-apply the sign ourselves so the
// truncation-toward-zero convention matches the shared Newton-Raphson fallback
// bit-for-bit, regardless of any PHP/GMP behaviour changes for negative inputs.
if ($n[0] === '-') {
return '-' . gmp_strval(gmp_root(substr($n, 1), $k));
}
return gmp_strval(gmp_root($n, $k));
}
}

View file

@ -0,0 +1,618 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Exception\PlatformException;
use Brick\Math\Internal\Calculator;
use Override;
use function assert;
use function in_array;
use function intdiv;
use function is_int;
use function ltrim;
use function str_pad;
use function str_repeat;
use function strcmp;
use function strlen;
use function substr;
use const PHP_INT_SIZE;
use const STR_PAD_LEFT;
/**
* Calculator implementation using only native PHP code.
*
* @internal
*/
final readonly class NativeCalculator extends Calculator
{
/**
* The max number of digits the platform can natively add, subtract, multiply or divide without overflow.
* For multiplication, this represents the max sum of the lengths of both operands.
*
* In addition, it is assumed that an extra digit can hold a carry (1) without overflowing.
* Example: 32-bit: max number 1,999,999,999 (9 digits + carry)
* 64-bit: max number 1,999,999,999,999,999,999 (18 digits + carry)
*/
private int $maxDigits;
/**
* @pure
*
* @codeCoverageIgnore
*/
public function __construct()
{
$this->maxDigits = match (PHP_INT_SIZE) {
4 => 9,
8 => 18, // @phpstan-ignore match.alwaysTrue
default => throw PlatformException::unsupportedIntSize(),
};
}
#[Override]
public function add(string $a, string $b): string
{
/**
* @var numeric-string $a
* @var numeric-string $b
*/
$result = $a + $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0') {
return $b;
}
if ($b === '0') {
return $a;
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig);
if ($aNeg) {
$result = $this->neg($result);
}
return $result;
}
#[Override]
public function sub(string $a, string $b): string
{
return $this->add($a, $this->neg($b));
}
#[Override]
public function mul(string $a, string $b): string
{
/**
* @var numeric-string $a
* @var numeric-string $b
*/
$result = $a * $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0' || $b === '0') {
return '0';
}
if ($a === '1') {
return $b;
}
if ($b === '1') {
return $a;
}
if ($a === '-1') {
return $this->neg($b);
}
if ($b === '-1') {
return $this->neg($a);
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$result = $this->doMul($aDig, $bDig);
if ($aNeg !== $bNeg) {
$result = $this->neg($result);
}
return $result;
}
#[Override]
public function divQ(string $a, string $b): string
{
return $this->divQR($a, $b)[0];
}
#[Override]
public function divR(string $a, string $b): string
{
return $this->divQR($a, $b)[1];
}
#[Override]
public function divQR(string $a, string $b): array
{
if ($a === '0') {
return ['0', '0'];
}
if ($a === $b) {
return ['1', '0'];
}
if ($b === '1') {
return [$a, '0'];
}
if ($b === '-1') {
return [$this->neg($a), '0'];
}
/** @var numeric-string $a */
$na = $a * 1; // cast to number
if (is_int($na)) {
/** @var numeric-string $b */
$nb = $b * 1;
if (is_int($nb)) {
// the only division that may overflow is PHP_INT_MIN / -1,
// which cannot happen here as we've already handled a divisor of -1 above.
$q = intdiv($na, $nb);
$r = $na % $nb;
return [
(string) $q,
(string) $r,
];
}
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
[$q, $r] = $this->doDiv($aDig, $bDig);
if ($aNeg !== $bNeg) {
$q = $this->neg($q);
}
if ($aNeg) {
$r = $this->neg($r);
}
return [$q, $r];
}
#[Override]
public function pow(string $a, int $e): string
{
if ($e === 0) {
return '1';
}
if ($e === 1) {
return $a;
}
$odd = $e % 2;
$e -= $odd;
$aa = $this->mul($a, $a);
$result = $this->pow($aa, $e / 2);
if ($odd === 1) {
$result = $this->mul($result, $a);
}
return $result;
}
/**
* Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/.
*/
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
// normalize to Euclidean representative so modPow() stays consistent with mod()
$base = $this->mod($base, $mod);
// special case: the algorithm below fails with power 0 mod 1 (returns 1 instead of 0)
if ($exp === '0' && $mod === '1') {
return '0';
}
$x = $base;
$res = '1';
// numbers are positive, so we can use remainder instead of modulo
$x = $this->divR($x, $mod);
while ($exp !== '0') {
if (in_array($exp[-1], ['1', '3', '5', '7', '9'])) { // odd
$res = $this->divR($this->mul($res, $x), $mod);
}
$exp = $this->divQ($exp, '2');
$x = $this->divR($this->mul($x, $x), $mod);
}
return $res;
}
/**
* Adapted from https://cp-algorithms.com/num_methods/roots_newton.html.
*/
#[Override]
public function sqrt(string $n): string
{
if ($n === '0') {
return '0';
}
// initial approximation
$x = str_repeat('9', intdiv(strlen($n), 2) ?: 1);
$decreased = false;
for (; ;) {
$nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
break;
}
$decreased = $this->cmp($nx, $x) < 0;
$x = $nx;
}
return $x;
}
/**
* Performs the addition of two non-signed large integers.
*
* @pure
*/
private function doAdd(string $a, string $b): string
{
[$a, $b, $length] = $this->pad($a, $b);
$carry = 0;
$result = '';
for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
/** @var numeric-string $blockA */
$blockA = substr($a, $i, $blockLength);
/** @var numeric-string $blockB */
$blockB = substr($b, $i, $blockLength);
$sum = (string) ($blockA + $blockB + $carry);
$sumLength = strlen($sum);
if ($sumLength > $blockLength) {
$sum = substr($sum, 1);
$carry = 1;
} else {
if ($sumLength < $blockLength) {
$sum = str_repeat('0', $blockLength - $sumLength) . $sum;
}
$carry = 0;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
if ($carry === 1) {
$result = '1' . $result;
}
return $result;
}
/**
* Performs the subtraction of two non-signed large integers.
*
* @pure
*/
private function doSub(string $a, string $b): string
{
if ($a === $b) {
return '0';
}
// Ensure that we always subtract to a positive result: biggest minus smallest.
$cmp = $this->doCmp($a, $b);
$invert = ($cmp === -1);
if ($invert) {
$c = $a;
$a = $b;
$b = $c;
}
[$a, $b, $length] = $this->pad($a, $b);
$carry = 0;
$result = '';
$complement = 10 ** $this->maxDigits;
for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
/** @var numeric-string $blockA */
$blockA = substr($a, $i, $blockLength);
/** @var numeric-string $blockB */
$blockB = substr($b, $i, $blockLength);
$sum = $blockA - $blockB - $carry;
if ($sum < 0) {
$sum += $complement;
$carry = 1;
} else {
$carry = 0;
}
$sum = (string) $sum;
$sumLength = strlen($sum);
if ($sumLength < $blockLength) {
$sum = str_repeat('0', $blockLength - $sumLength) . $sum;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
// Carry cannot be 1 when the loop ends, as a > b
assert($carry === 0);
$result = ltrim($result, '0');
if ($invert) {
$result = $this->neg($result);
}
return $result;
}
/**
* Performs the multiplication of two non-signed large integers.
*
* @pure
*/
private function doMul(string $a, string $b): string
{
$x = strlen($a);
$y = strlen($b);
$maxDigits = intdiv($this->maxDigits, 2);
$complement = 10 ** $maxDigits;
$result = '0';
for ($i = $x - $maxDigits; ; $i -= $maxDigits) {
$blockALength = $maxDigits;
if ($i < 0) {
$blockALength += $i;
$i = 0;
}
$blockA = (int) substr($a, $i, $blockALength);
$line = '';
$carry = 0;
for ($j = $y - $maxDigits; ; $j -= $maxDigits) {
$blockBLength = $maxDigits;
if ($j < 0) {
$blockBLength += $j;
$j = 0;
}
$blockB = (int) substr($b, $j, $blockBLength);
$mul = $blockA * $blockB + $carry;
$value = $mul % $complement;
$carry = ($mul - $value) / $complement;
$value = (string) $value;
$value = str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
$line = $value . $line;
if ($j === 0) {
break;
}
}
if ($carry !== 0) {
$line = $carry . $line;
}
$line = ltrim($line, '0');
if ($line !== '') {
$line .= str_repeat('0', $x - $blockALength - $i);
$result = $this->add($result, $line);
}
if ($i === 0) {
break;
}
}
return $result;
}
/**
* Performs the division of two non-signed large integers.
*
* @return string[] The quotient and remainder.
*
* @pure
*/
private function doDiv(string $a, string $b): array
{
$cmp = $this->doCmp($a, $b);
if ($cmp === -1) {
return ['0', $a];
}
$x = strlen($a);
$y = strlen($b);
// we now know that a >= b && x >= y
$q = '0'; // quotient
$r = $a; // remainder
$z = $y; // focus length, always $y or $y+1
/** @var numeric-string $b */
$nb = $b * 1; // cast to number
// performance optimization in cases where the remainder will never cause int overflow
if (is_int(($nb - 1) * 10 + 9)) {
$r = (int) substr($a, 0, $z - 1);
for ($i = $z - 1; $i < $x; $i++) {
$n = $r * 10 + (int) $a[$i];
/** @var int $nb */
$q .= intdiv($n, $nb);
$r = $n % $nb;
}
return [ltrim($q, '0') ?: '0', (string) $r];
}
for (; ;) {
$focus = substr($a, 0, $z);
$cmp = $this->doCmp($focus, $b);
if ($cmp === -1) {
if ($z === $x) { // remainder < dividend
break;
}
$z++;
}
$zeros = str_repeat('0', $x - $z);
$q = $this->add($q, '1' . $zeros);
$a = $this->sub($a, $b . $zeros);
$r = $a;
if ($r === '0') { // remainder == 0
break;
}
$x = strlen($a);
if ($x < $y) { // remainder < dividend
break;
}
$z = $y;
}
return [$q, $r];
}
/**
* Compares two non-signed large numbers.
*
* @return -1|0|1
*
* @pure
*/
private function doCmp(string $a, string $b): int
{
$x = strlen($a);
$y = strlen($b);
$cmp = $x <=> $y;
if ($cmp !== 0) {
return $cmp;
}
return strcmp($a, $b) <=> 0; // enforce -1|0|1
}
/**
* Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length.
*
* The numbers must only consist of digits, without leading minus sign.
*
* @return array{string, string, int}
*
* @pure
*/
private function pad(string $a, string $b): array
{
$x = strlen($a);
$y = strlen($b);
if ($x > $y) {
$b = str_repeat('0', $x - $y) . $b;
return [$a, $b, $x];
}
if ($x < $y) {
$a = str_repeat('0', $y - $x) . $a;
return [$a, $b, $y];
}
return [$a, $b, $x];
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use function extension_loaded;
/**
* Stores the current Calculator instance used by BigNumber classes.
*
* @internal
*/
final class CalculatorRegistry
{
/**
* The Calculator instance in use.
*/
private static ?Calculator $instance = null;
/**
* Sets the Calculator instance to use.
*
* An instance is typically set only in unit tests: autodetect is usually the best option.
*
* @param Calculator|null $calculator The calculator instance, or null to revert to autodetect.
*/
final public static function set(?Calculator $calculator): void
{
self::$instance = $calculator;
}
/**
* Returns the Calculator instance to use.
*
* If none has been explicitly set, the fastest available implementation will be returned.
*
* Note: even though this method is not technically pure, it is considered pure when used in a normal context, when
* only relying on autodetect.
*
* @pure
*/
final public static function get(): Calculator
{
/** @phpstan-ignore impure.staticPropertyAccess */
if (self::$instance === null) {
/** @phpstan-ignore impure.propertyAssign */
self::$instance = self::detect();
}
/** @phpstan-ignore impure.staticPropertyAccess */
return self::$instance;
}
/**
* Returns the fastest available Calculator implementation.
*
* @pure
*
* @codeCoverageIgnore
*/
private static function detect(): Calculator
{
if (extension_loaded('gmp')) {
return new Calculator\GmpCalculator();
}
if (extension_loaded('bcmath')) {
return new Calculator\BcMathCalculator();
}
return new Calculator\NativeCalculator();
}
}

View file

@ -0,0 +1,180 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\RoundingMode;
use function ltrim;
use function rtrim;
use function str_pad;
use function str_repeat;
use function strlen;
use function substr;
use const STR_PAD_LEFT;
/**
* Shared helper for decimal operations.
*
* @internal
*/
final class DecimalHelper
{
/**
* @codeCoverageIgnore
*/
private function __construct()
{
}
/**
* Computes the scale needed to represent the exact decimal result of a reduced fraction.
*
* Returns null if the denominator has prime factors other than 2 or 5.
*
* @param string $denominator The denominator of the reduced fraction. Must be strictly positive.
*
* @return non-negative-int|null
*
* @pure
*/
public static function computeScaleFromReducedFractionDenominator(string $denominator): ?int
{
$calculator = CalculatorRegistry::get();
$d = rtrim($denominator, '0');
/** @var non-negative-int $scale rtrim can only shorten a string */
$scale = strlen($denominator) - strlen($d);
foreach ([5, 2] as $prime) {
for (; ;) {
$lastDigit = (int) $d[-1];
if ($lastDigit % $prime !== 0) {
break;
}
$d = $calculator->divQ($d, (string) $prime);
$scale++;
}
}
return $d === '1' ? $scale : null;
}
/**
* Scales an unscaled decimal value to the requested scale.
*
* Returns null when rounding is necessary and the rounding mode is Unnecessary.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
* @param RoundingMode $roundingMode The rounding mode.
*
* @return string|null The unscaled value at the target scale, or null if RoundingMode::Unnecessary is used and rounding is necessary.
*
* @pure
*/
public static function scale(string $value, int $currentScale, int $targetScale, RoundingMode $roundingMode): ?string
{
$scaled = self::tryScaleExactly($value, $currentScale, $targetScale);
if ($scaled !== null) {
return $scaled;
}
if ($roundingMode === RoundingMode::Unnecessary) {
return null;
}
$divisor = '1' . str_repeat('0', $currentScale - $targetScale);
return CalculatorRegistry::get()->divRound($value, $divisor, $roundingMode);
}
/**
* Adds leading zeros if necessary to represent the full decimal number.
*
* @param string $value The unscaled value.
* @param int $scale The current scale.
*
* @pure
*/
public static function padUnscaledValue(string $value, int $scale): string
{
$targetLength = $scale + 1;
$negative = ($value[0] === '-');
$length = strlen($value);
if ($negative) {
$length--;
}
if ($length >= $targetLength) {
return $value;
}
if ($negative) {
$value = substr($value, 1);
}
$value = str_pad($value, $targetLength, '0', STR_PAD_LEFT);
if ($negative) {
$value = '-' . $value;
}
return $value;
}
/**
* Tries to scale exactly without rounding, returning null when rounding would be required.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
*
* @return string|null The unscaled value at the target scale, or null if rounding would be required.
*
* @pure
*/
public static function tryScaleExactly(string $value, int $currentScale, int $targetScale): ?string
{
if ($value === '0' || $targetScale === $currentScale) {
return $value;
}
if ($targetScale > $currentScale) {
return $value . str_repeat('0', $targetScale - $currentScale);
}
$negative = ($value[0] === '-');
if ($negative) {
$value = substr($value, 1);
}
$value = self::padUnscaledValue($value, $currentScale);
$discardedDigits = $currentScale - $targetScale;
if (substr($value, -$discardedDigits) !== str_repeat('0', $discardedDigits)) {
return null;
}
$value = substr($value, 0, -$discardedDigits);
$value = ltrim($value, '0');
if ($value === '') {
return '0';
}
if ($negative) {
$value = '-' . $value;
}
return $value;
}
}

84
vendor/brick/math/src/Internal/Safe.php vendored Normal file
View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\Exception\IntegerOverflowException;
use function is_int;
use function sprintf;
use const PHP_INT_MIN;
/**
* Helpers for arithmetic operations that throw on native integer overflow.
*
* @internal
*/
final class Safe
{
/**
* @codeCoverageIgnore
*/
private function __construct()
{
}
/**
* @pure
*/
public static function add(int $a, int $b): int
{
$result = $a + $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d + %d', $a, $b));
}
/**
* @pure
*/
public static function sub(int $a, int $b): int
{
$result = $a - $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d - %d', $a, $b));
}
/**
* @pure
*/
public static function mul(int $a, int $b): int
{
$result = $a * $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d * %d', $a, $b));
}
/**
* @pure
*/
public static function neg(int $value): int
{
if ($value === PHP_INT_MIN) {
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('-(%d)', $value));
}
return -$value;
}
}

75
vendor/brick/math/src/NumberSyntax.php vendored Normal file
View file

@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
/**
* A syntax feature that {@see BigNumber::parse()} can accept.
*
* Plain signed integers such as `123` and `-7` are the base language: they are always accepted.
* Each case allows one additional feature:
*
* - DecimalPoint: `.`
* - Exponent: `e` or `E`
* - Fraction: `/`
*
* In addition to its cases, this enum provides list constants for the most common combinations, from INTEGER to ALL.
*/
enum NumberSyntax
{
/**
* Allows the decimal point: `1.5`, `.5`, `1.`.
*/
case DecimalPoint;
/**
* Allows the exponent: `5e3`, `15E-2`.
*/
case Exponent;
/**
* Allows the fraction form: `2/4`. The numerator and denominator are unsigned integers; an optional sign
* precedes the whole fraction.
*/
case Fraction;
/**
* Integers only: `123`.
* The base language, with no additional notation.
*/
public const INTEGER = [];
/**
* Integers and decimal numbers: `123`, `123.45`.
* Typical for monetary input.
*/
public const DECIMAL = [
self::DecimalPoint,
];
/**
* Integers and decimal numbers, with exponents: `123`, `123.45`, `1.5e-3`.
* Accepts every JSON number.
*/
public const SCIENTIFIC = [
self::DecimalPoint,
self::Exponent,
];
/**
* Integers and fractions: `123`, `22/7`.
*/
public const RATIONAL = [
self::Fraction,
];
/**
* The full syntax accepted by {@see BigNumber::of()}: `123`, `123.45`, `1.5e-3`, `22/7`.
*/
public const ALL = [
self::DecimalPoint,
self::Exponent,
self::Fraction,
];
}

147
vendor/brick/math/src/RoundingMode.php vendored Normal file
View file

@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
/**
* Specifies rounding behavior by defining how discarded digits affect the returned result when an exact value cannot
* be represented at the requested scale.
*/
enum RoundingMode
{
/**
* Asserts that the requested operation has an exact result, hence no rounding is necessary.
*
* If this rounding mode is specified on an operation that yields a result that
* cannot be represented at the requested scale, a RoundingNecessaryException is thrown.
*
* Equivalent native PHP rounding mode: none.
*/
case Unnecessary;
/**
* Rounds away from zero.
*
* Always increments the digit prior to a nonzero discarded fraction.
* Note that this rounding mode never decreases the magnitude of the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::AwayFromZero}.
*/
case Up;
/**
* Rounds towards zero.
*
* Never increments the digit prior to a discarded fraction (i.e., truncates).
* Note that this rounding mode never increases the magnitude of the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::TowardsZero}.
*/
case Down;
/**
* Rounds towards positive infinity.
*
* If the result is positive, behaves as for Up; if negative, behaves as for Down.
* Note that this rounding mode never decreases the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::PositiveInfinity}.
*/
case Ceiling;
/**
* Rounds towards negative infinity.
*
* If the result is positive, behaves as for Down; if negative, behaves as for Up.
* Note that this rounding mode never increases the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::NegativeInfinity}.
*/
case Floor;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
*
* Behaves as for Up if the discarded fraction is >= 0.5; otherwise, behaves as for Down.
* Note that this is the rounding mode commonly taught at school.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfAwayFromZero}.
*/
case HalfUp;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
*
* Behaves as for Up if the discarded fraction is > 0.5; otherwise, behaves as for Down.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfTowardsZero}.
*/
case HalfDown;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity.
*
* If the result is positive, behaves as for HalfUp; if negative, behaves as for HalfDown.
*
* Equivalent native PHP rounding mode: none.
*/
case HalfCeiling;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity.
*
* If the result is positive, behaves as for HalfDown; if negative, behaves as for HalfUp.
*
* Equivalent native PHP rounding mode: none.
*/
case HalfFloor;
/**
* Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor.
*
* Behaves as for HalfUp if the digit to the left of the discarded fraction is odd;
* behaves as for HalfDown if it's even.
*
* Note that this is the rounding mode that statistically minimizes
* cumulative error when applied repeatedly over a sequence of calculations.
* It is sometimes known as "Banker's rounding", and is the default rounding mode in IEEE 754.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfEven}.
*/
case HalfEven;
/**
* Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the odd neighbor.
*
* Behaves as for HalfUp if the digit to the left of the discarded fraction is even;
* behaves as for HalfDown if it's odd.
*
* Like HalfEven, this rounding mode is free of bias towards or away from zero on ties;
* unlike HalfEven, ties never round to an even digit — in particular, never to zero or to a multiple of ten.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfOdd}.
*/
case HalfOdd;
/**
* Returns the equivalent of the given native PHP rounding mode.
*
* Note that PHP's RoundingMode enum is only available on PHP 8.4 and later.
*
* @pure
*/
public static function fromNativeRoundingMode(\RoundingMode $roundingMode): self
{
return match ($roundingMode) {
\RoundingMode::AwayFromZero => self::Up,
\RoundingMode::TowardsZero => self::Down,
\RoundingMode::PositiveInfinity => self::Ceiling,
\RoundingMode::NegativeInfinity => self::Floor,
\RoundingMode::HalfAwayFromZero => self::HalfUp,
\RoundingMode::HalfTowardsZero => self::HalfDown,
\RoundingMode::HalfEven => self::HalfEven,
\RoundingMode::HalfOdd => self::HalfOdd,
};
}
}