### Install Brick Math using Composer Source: https://github.com/brick/math/blob/main/README.md Use Composer to install the library. This command adds the brick/math package to your project's dependencies. ```bash composer require brick/math ``` -------------------------------- ### Install BCMath Extension on Alpine Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the BCMath extension on Alpine Linux systems using apk. Adjust the PHP version in the command as needed. ```bash apk add php82-bcmath ``` -------------------------------- ### Install BCMath Extension on Debian/Ubuntu Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the BCMath extension on Debian or Ubuntu systems using apt-get. This extension is a fast alternative if GMP is unavailable. ```bash sudo apt-get install php-bcmath ``` -------------------------------- ### Install GMP Extension on Debian/Ubuntu Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the GMP extension on Debian or Ubuntu systems using apt-get. This extension provides the fastest performance for mathematical operations. ```bash sudo apt-get install php-gmp ``` -------------------------------- ### Install GMP Extension on Alpine Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the GMP extension on Alpine Linux systems using apk. Adjust the PHP version in the command as needed. ```bash apk add php82-gmp # Adjust version as needed ``` -------------------------------- ### Install BCMath Extension on CentOS/RHEL Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the BCMath extension on CentOS or RHEL systems using yum. This extension is a fast alternative if GMP is unavailable. ```bash sudo yum install php-bcmath ``` -------------------------------- ### Catching MathException Example Source: https://github.com/brick/math/blob/main/_autodocs/types.md Demonstrates how to catch any exception that implements the MathException interface. This is useful for general error handling of library operations. ```php use Brick\Math\Exception\MathException; try { $result = BigInteger::of('not a number'); } catch (MathException $e) { // Handle any math exception } ``` -------------------------------- ### Install GMP Extension on macOS Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the GMP extension on macOS using Homebrew and PECL. This extension provides the fastest performance for mathematical operations. ```bash # Using Homebrew brew install gmp pecl install gmp ``` -------------------------------- ### Autoloading with Composer Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md The library uses PSR-4 autoloading. Once installed via Composer, you can import its classes directly. ```php // Automatically loaded by Composer use Brick\Math\BigInteger; use Brick\Math\BigDecimal; use Brick\Math\BigRational; use Brick\Math\RoundingMode; ``` -------------------------------- ### HalfEven Rounding Examples Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Illustrates the behavior of RoundingMode::HalfEven with various fractional values, showing how it rounds to the nearest even neighbor when equidistant. ```php RoundingMode::HalfEven with various fractions: 0.5 → 0 (between 0 and 1, digit left of .5 is 0 [even], so round to 0) 1.5 → 2 (between 1 and 2, digit left of .5 is 1 [odd], so round to 2) 2.5 → 2 (between 2 and 3, digit left of .5 is 2 [even], so round to 2) 3.5 → 4 (between 3 and 4, digit left of .5 is 3 [odd], so round to 4) 4.5 → 4 (between 4 and 5, digit left of .5 is 4 [even], so round to 4) ``` -------------------------------- ### Install GMP Extension on CentOS/RHEL Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Install the GMP extension on CentOS or RHEL systems using yum. This extension provides the fastest performance for mathematical operations. ```bash sudo yum install php-gmp ``` -------------------------------- ### Catching Math-Related Exceptions Source: https://github.com/brick/math/blob/main/_autodocs/README.md Provides an example of how to handle specific and general math exceptions using a try-catch block. ```php use Brick\Math\Exception\MathException; use Brick\Math\Exception\DivisionByZeroException; use Brick\Math\Exception\RoundingNecessaryException; try { $result = doMath(); } catch (DivisionByZeroException $e) { // Handle specific case } catch (RoundingNecessaryException $e) { // Handle rounding error } catch (MathException $e) { // Catch any other math error } ``` -------------------------------- ### Force Native Calculator (Not Recommended) Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md For testing or debugging purposes only, you can force the use of the NativeCalculator. It is generally recommended to install the appropriate PHP extension for better performance. ```php // NOT RECOMMENDED - for testing/debugging only // Users should install the appropriate PHP extension instead use Brick\Math\Internal\CalculatorRegistry; use Brick\Math\Internal\Calculator\NativeCalculator; // Force native calculator (slowest) CalculatorRegistry::set(new NativeCalculator()); ``` -------------------------------- ### Get the reciprocal of a BigRational number using reciprocal() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Use the reciprocal() method to get the multiplicative inverse of the current BigRational number. This is equivalent to calling power(-1). Division by zero will occur if the number is zero. ```php BigRational::of('2/3')->reciprocal(); // 3/2 BigRational::of(5)->reciprocal(); // 1/5 BigRational::of('1/10')->reciprocal(); // 10/1 // Zero has no reciprocal BigRational::of(0)->reciprocal(); // throws DivisionByZeroException ``` -------------------------------- ### Division Operations with Different Rounding Modes Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Demonstrates how to perform division operations using various RoundingMode constants in Brick Math's BigDecimal. Shows an example that throws an exception for RoundingMode::Unnecessary. ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; $dividend = BigDecimal::of(10); $divisor = BigDecimal::of(3); $scale = 2; // Different rounding modes for 10 / 3 $dividend->dividedBy($divisor, $scale, RoundingMode::Unnecessary); // throws RoundingNecessaryException $dividend->dividedBy($divisor, $scale, RoundingMode::Down); // 3.33 $dividend->dividedBy($divisor, $scale, RoundingMode::Up); // 3.34 $dividend->dividedBy($divisor, $scale, RoundingMode::HalfUp); // 3.33 $dividend->dividedBy($divisor, $scale, RoundingMode::Ceiling); // 3.34 $dividend->dividedBy($divisor, $scale, RoundingMode::Floor); // 3.33 ``` -------------------------------- ### Financial Calculation with BigDecimal Source: https://github.com/brick/math/blob/main/_autodocs/README.md Example of using BigDecimal for financial calculations, including applying tax and calculating the total price. It emphasizes using explicit scale and HalfUp rounding mode. ```php $price = BigDecimal::of('19.99'); $tax = $price->multipliedBy('0.08')->withScale(2, RoundingMode::HalfUp); $total = $price->plus($tax); // 21.59 ``` -------------------------------- ### Get cached BigInteger instances for 0, 1, and 10 Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Use BigInteger::zero(), BigInteger::one(), and BigInteger::ten() to retrieve cached instances of these common values. This is efficient for repeated use. ```PHP $zero = BigInteger::zero(); $zero->isZero(); // true ``` ```PHP $one = BigInteger::one(); ``` ```PHP $ten = BigInteger::ten(); ``` -------------------------------- ### Get Euclidean remainder using remainder() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Retrieve the remainder of Euclidean division using the `remainder()` method. The sign of the remainder will match the sign of the dividend. ```php BigInteger::of(7)->remainder(3); BigInteger::of(7)->remainder(-3); BigInteger::of(-7)->remainder(3); BigInteger::of(-7)->remainder(-3); ``` -------------------------------- ### Get Euclidean quotient using quotient() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Obtain the quotient of Euclidean division, truncated toward zero, using the `quotient()` method. This differs from the `//` operator which rounds down. ```php BigInteger::of(7)->quotient(3); BigInteger::of(7)->quotient(-3); BigInteger::of(-7)->quotient(3); BigInteger::of(-7)->quotient(-3); ``` -------------------------------- ### BigInteger Division: Exact vs. Rounding Source: https://github.com/brick/math/blob/main/README.md Demonstrates BigInteger division, showing the default behavior which throws an exception for non-zero remainders, and how to use rounding modes. ```php echo BigInteger::of(999)->dividedBy(3); // 333 echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException ``` ```php echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Down); // 333 echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Up); // 334 ``` -------------------------------- ### Handle Math Exceptions Source: https://github.com/brick/math/blob/main/_autodocs/README.md Demonstrates how to catch MathException, which can be thrown for operations like division by zero. ```php use Brick\Math\Exception\MathException; try { $result = BigInteger::of(10)->dividedBy(0); } catch (MathException $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Exact Fractional Math with BigRational Source: https://github.com/brick/math/blob/main/_autodocs/README.md Shows how to perform exact arithmetic with fractions using BigRational. The library automatically reduces fractions to their lowest terms and supports operations like addition. ```php $a = BigRational::of('1/3'); $b = BigRational::of('2/5'); $result = $a->plus($b); // 11/15 ``` -------------------------------- ### Get Denominator of BigRational Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Retrieves the denominator of a BigRational number. The denominator is always strictly positive. ```php $rat = BigRational::of('2/3'); $rat->getDenominator(); // BigInteger(3) $neg = BigRational::of('-2/3'); $neg->getDenominator(); // BigInteger(3) - always positive ``` -------------------------------- ### Get JSON-serializable string representation of BigNumber Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigNumber.md Returns a JSON-serializable string representation of this number, which is the same as the output of `toString()`. ```php $num = BigInteger::of(42); json_encode(['value' => $num]); // '{"value":"42"}' ``` -------------------------------- ### Get Numerator of BigRational Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Retrieves the numerator of a BigRational number. The sign of the rational number is carried by the numerator. ```php $rat = BigRational::of('2/3'); $rat->getNumerator(); // BigInteger(2) $neg = BigRational::of('-2/3'); $neg->getNumerator(); // BigInteger(-2) ``` -------------------------------- ### Create BigInteger, BigDecimal, and BigRational Numbers Source: https://github.com/brick/math/blob/main/_autodocs/README.md Demonstrates how to create instances of BigInteger, BigDecimal, and BigRational. BigIntegers can be created from integers or strings, while BigDecimals require explicit scale and BigRationals are automatically simplified. ```php use Brick\Math\BigInteger; use Brick\Math\BigDecimal; use Brick\Math\BigRational; // Integers $a = BigInteger::of(123); $b = BigInteger::of('999999999999999999999'); // Decimals (with explicit scale) $c = BigDecimal::of('3.14159'); $d = BigDecimal::of('1e-5'); // Rationals (automatically simplified) $e = BigRational::of('2/3'); $f = BigRational::of('1.15'); // Becomes 23/20 ``` -------------------------------- ### Get string representation of BigNumber Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigNumber.md Returns the string representation of this number. This string can be parsed by `of()` to recreate an equivalent object. ```php BigInteger::of(42)->toString(); // '42' BigDecimal::of('1.5')->toString(); // '1.5' BigRational::of('2/3')->toString(); // '2/3' ``` -------------------------------- ### Catching Brick Math Exceptions Source: https://github.com/brick/math/blob/main/README.md Shows how to catch all exceptions thrown by the library using the MathException interface, or specific exception classes for more granular control. ```php use Brick\Math\BigDecimal; use Brick\Math\Exception\MathException; try { $number = BigInteger::of(1)->dividedBy(3); } catch (MathException $e) { // ... } ``` -------------------------------- ### Get Scale of BigDecimal Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigDecimal.md Retrieves the number of decimal places in a BigDecimal. Preserves trailing zeros in the scale calculation. ```php BigDecimal::of('1.5')->getScale(); // 1 BigDecimal::of('3.14159')->getScale(); // 5 BigDecimal::of('42')->getScale(); // 0 BigDecimal::of('0.00100')->getScale(); // 5 (preserves trailing zeros) ``` -------------------------------- ### BigInteger::ten() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Returns a cached instance of BigInteger representing the value 10. This is an efficient way to get a ten value. ```APIDOC ## BigInteger::ten() ### Description Returns a cached BigInteger(10) instance. ### Method `public static function ten(): BigInteger` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $ten = BigInteger::ten(); ``` ### Response #### Success Response (200) `BigInteger` - Immutable ten instance. #### Response Example None provided. ``` -------------------------------- ### Correct Usage of Factory Methods - Brick\Math Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Use factory methods like BigInteger::of(), BigDecimal::of(), and BigRational::of() for creating instances. Direct instantiation via constructors is not supported and will result in a PHP Fatal Error. ```php // Correct usage - factory methods $a = BigInteger::of(42); $b = BigDecimal::of('3.14'); $c = BigRational::of('2/3'); // These do NOT work - constructors are protected $x = new BigInteger(42); // PHP Fatal Error $y = new BigDecimal('3.14'); // PHP Fatal Error $z = new BigRational(1, 2); // PHP Fatal Error ``` -------------------------------- ### BigInteger::one() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Returns a cached instance of BigInteger representing the value 1. This is an efficient way to get a one value. ```APIDOC ## BigInteger::one() ### Description Returns a cached BigInteger(1) instance. ### Method `public static function one(): BigInteger` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $one = BigInteger::one(); ``` ### Response #### Success Response (200) `BigInteger` - Immutable one instance. #### Response Example None provided. ``` -------------------------------- ### BigInteger::zero() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Returns a cached instance of BigInteger representing the value 0. This is an efficient way to get a zero value. ```APIDOC ## BigInteger::zero() ### Description Returns a cached BigInteger(0) instance. ### Method `public static function zero(): BigInteger` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $zero = BigInteger::zero(); $zero->isZero(); // true ``` ### Response #### Success Response (200) `BigInteger` - Immutable zero instance. #### Response Example None provided. ``` -------------------------------- ### Get Lowest Set Bit Index Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Finds the index of the rightmost '1' bit in a BigInteger. Returns null if the number is zero. ```php BigInteger::of(0)->getLowestSetBit(); // null ``` ```php BigInteger::of(1)->getLowestSetBit(); // 0 (binary: 1) ``` ```php BigInteger::of(4)->getLowestSetBit(); // 2 (binary: 100) ``` ```php BigInteger::of(12)->getLowestSetBit(); // 2 (binary: 1100) ``` -------------------------------- ### Immutability and Chaining with BigInteger Source: https://github.com/brick/math/blob/main/README.md Demonstrates the immutable nature of BigInteger objects and how methods can be chained for concise operations. Original objects remain unaffected. ```php $ten = BigInteger::of(10); echo $ten->plus(5); // 15 echo $ten->multipliedBy(3); // 30 ``` ```php echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45 ``` -------------------------------- ### Usage in Currency Calculations Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Illustrates using RoundingMode::HalfUp for currency calculations, highlighting potential discrepancies when rounding individual amounts versus the total. ```APIDOC ### In Currency Calculations ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; // Divide a bill equally among 3 people $total = BigDecimal::of('29.99'); $perPerson = $total->dividedBy(3, 2, RoundingMode::HalfUp); echo $perPerson; // 10.00 (each person pays) // But 3 × 10.00 = 30.00, not 29.99! // Need to round differently to match total ``` ``` -------------------------------- ### Get Bit Length Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Retrieves the number of bits required for the minimal two's-complement representation of a BigInteger. Returns 0 for zero and negative one. ```php BigInteger::of(0)->getBitLength(); // 0 ``` ```php BigInteger::of(7)->getBitLength(); // 3 (binary: 111) ``` ```php BigInteger::of(8)->getBitLength(); // 4 (binary: 1000) ``` ```php BigInteger::of(-1)->getBitLength(); // 0 ``` ```php BigInteger::of(-8)->getBitLength(); // 4 ``` -------------------------------- ### Catching DivisionByZeroException in PHP Source: https://github.com/brick/math/blob/main/_autodocs/errors.md Demonstrates how to catch a DivisionByZeroException when performing an operation that results in division by zero. Ensure the Brick\Math\Exception namespace is imported. ```php use Brick\Math\BigInteger; use Brick\Math\Exception\DivisionByZeroException; try { BigInteger::of(10)->dividedBy(0); } catch (DivisionByZeroException $e) { echo "Cannot divide by zero: " . $e->getMessage(); } ``` -------------------------------- ### Automatic Simplification of BigRational Source: https://github.com/brick/math/blob/main/_autodocs/README.md Demonstrates how BigRational objects are automatically reduced to their simplest form upon creation. ```php BigRational::of('6/9'); // Becomes 2/3 BigRational::of('10/25'); // Becomes 2/5 ``` -------------------------------- ### BigInteger Class Documentation Source: https://github.com/brick/math/blob/main/_autodocs/MANIFEST.txt Documentation for the BigInteger class, supporting arbitrary-precision integers with methods for base conversion, arithmetic, bitwise operations, and more. ```APIDOC ## BigInteger Class ### Description Represents arbitrary-precision integers. Supports a wide range of arithmetic, bitwise, and conversion operations. ### Factory Methods - **of(value):** Creates a BigInteger from a string or integer. - **zero():** Returns a BigInteger representing zero. - **one():** Returns a BigInteger representing one. - **ten():** Returns a BigInteger representing ten. ### Base Conversion - **fromBase(value, base):** Creates a BigInteger from a string representation in a given base. - **fromArbitraryBase(value, base):** Creates a BigInteger from a string representation in an arbitrary base. - **toBase(base):** Converts this BigInteger to a string representation in the specified base. - **toArbitraryBase(base):** Converts this BigInteger to a string representation in an arbitrary base. ### Byte Conversion - **fromBytes(bytes):** Creates a BigInteger from a byte string. - **toBytes():** Converts this BigInteger to a byte string. ### Random Generation - **randomBits(numBits):** Generates a random BigInteger with a specified number of bits. - **randomRange(min, max):** Generates a random BigInteger within a specified range. ### GCD and LCM - **gcd(a, b):** Computes the greatest common divisor of two BigIntegers. - **lcm(a, b):** Computes the least common multiple of two BigIntegers. - **gcdAll(numbers):** Computes the GCD of an array of BigIntegers. - **lcmAll(numbers):** Computes the LCM of an array of BigIntegers. ### Arithmetic Operations - **plus(other):** Adds another BigInteger to this one. - **minus(other):** Subtracts another BigInteger from this one. - **multipliedBy(other):** Multiplies this BigInteger by another. - **dividedBy(other):** Divides this BigInteger by another (returns BigNumber). ### Power Operations - **power(exponent):** Raises this BigInteger to a non-negative integer exponent. - **modPow(exponent, modulus):** Computes (this^exponent) % modulus. ### Root Operations - **sqrt():** Computes the integer square root of this BigInteger. - **nthRoot(nth):** Computes the integer nth root of this BigInteger. ### Division Operations - **quotient(other):** Returns the quotient of the division. - **remainder(other):** Returns the remainder of the division. - **quotientAndRemainder(other):** Returns an object containing both quotient and remainder. ### Modular Arithmetic - **mod(modulus):** Computes this BigInteger modulo the given modulus. - **modInverse(modulus):** Computes the modular multiplicative inverse. ### Bitwise Operations - **and(other):** Performs a bitwise AND operation. - **or(other):** Performs a bitwise OR operation. - **xor(other):** Performs a bitwise XOR operation. - **not():** Performs a bitwise NOT operation. ### Bit Operations - **shiftedLeft(numBits):** Shifts the bits to the left. - **shiftedRight(numBits):** Shifts the bits to the right. - **getBitLength():** Returns the number of bits required to represent this BigInteger. ### Bit Queries - **getLowestSetBit():** Returns the index of the lowest set bit. - **isBitSet(bitIndex):** Checks if a specific bit is set. ### Parity Checks - **isEven():** Checks if the BigInteger is even. - **isOdd():** Checks if the BigInteger is odd. ``` -------------------------------- ### Get Unscaled Value of BigDecimal Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigDecimal.md Returns the unscaled value (mantissa) as a BigInteger. To reconstruct the decimal, divide the unscaled value by 10 raised to the power of the scale. ```php $dec = BigDecimal::of('12.345'); $unscaled = $dec->getUnscaledValue(); // BigInteger(12345) $scale = $dec->getScale(); // 5 // Reconstruct: 12345 / 10^5 = 0.12345... wait, wrong scale // Should be: 12345 / 10^3 = 12.345 (scale = 3) ``` -------------------------------- ### Catch All Brick\u2014Math Exceptions Source: https://github.com/brick/math/blob/main/_autodocs/errors.md Use a general `MathException` catch block to handle any errors originating from the Brick\u2014Math library. This is useful for unexpected issues or when specific error types are not critical to differentiate. ```php use Brick\Math\BigInteger; use Brick\Math\Exception\MathException; try { $result = BigInteger::of('invalid')->plus(BigInteger::of(10)->dividedBy(0)); } catch (MathException $e) { // Catches ANY exception from Brick\u2014Math echo "Math error: " . $e->getMessage(); } ``` -------------------------------- ### Divide BigDecimal with Rounding Source: https://github.com/brick/math/blob/main/_autodocs/README.md Shows how to perform division with BigDecimal, including cases with and without explicit rounding modes. Using a rounding mode is necessary when the division results in an inexact number. ```php use Brick\Math\RoundingMode; $a = BigDecimal::of(1); $b = BigDecimal::of(3); // Without rounding (throws if inexact) $result = $a->dividedBy($b, 10); // RoundingNecessaryException // With rounding mode $result = $a->dividedBy($b, 10, RoundingMode::HalfUp); // 0.3333333333 ``` -------------------------------- ### RoundingMode::Unnecessary Example Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Use RoundingMode::Unnecessary when the result is expected to be exact. It throws a RoundingNecessaryException if rounding is required, helping to catch unexpected remainders early. ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; // Exact division BigDecimal::of(1)->dividedBy(2, 1, RoundingMode::Unnecessary); // 0.5 // Inexact division BigDecimal::of(1)->dividedBy(3, 2, RoundingMode::Unnecessary); // throws RoundingNecessaryException ``` -------------------------------- ### Demonstrate Immutability of BigInteger Source: https://github.com/brick/math/blob/main/_autodocs/README.md Shows that operations on BigInteger objects return new instances, leaving the original unchanged. ```php $original = BigInteger::of(10); $modified = $original->plus(5); // $original is still 10 // $modified is 15 ``` -------------------------------- ### Get Quotient and Remainder with BigInteger Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Use quotientAndRemainder() to efficiently compute both the quotient and remainder of a division in a single operation. This method is useful when both results are needed to avoid redundant calculations. ```php [$q, $r] = BigInteger::of(1000)->quotientAndRemainder(3); // $q = BigInteger(333), $r = BigInteger(1) [$q, $r] = BigInteger::of(-7)->quotientAndRemainder(3); // $q = BigInteger(-2), $r = BigInteger(-1) ``` -------------------------------- ### BigDecimal Scale Handling Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Demonstrates how BigDecimal preserves scale explicitly and how arithmetic operations affect scale. Trailing zeros are preserved. ```php use Brick\Math\BigDecimal; $a = BigDecimal::of('1.5'); // scale = 1 $b = BigDecimal::of('1.50'); // scale = 2 (trailing zero preserved) $c = BigDecimal::of('1'); // scale = 0 $d = BigDecimal::of('1.0'); // scale = 1 // Arithmetic preserves or increases scale $result = $a->plus($b); // scale = 2 (max of inputs) $result = $a->multipliedBy($b); // scale = 3 (sum of scales) ``` -------------------------------- ### Get Absolute Value of BigNumber Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigNumber.md The `abs()` method returns a new number representing the absolute value of the original. Use this when you need to work with the magnitude of a number, ignoring its sign. ```php BigInteger::of(-42)->abs(); // BigInteger(42) BigDecimal::of('-1.5')->abs(); // BigDecimal('1.5') ``` -------------------------------- ### Check the active calculator implementation Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md You can check which calculator implementation (GMP, BCMath, or Native PHP) is currently being used by the library. This is useful for performance diagnostics. ```php // Check which calculator is in use $calculator = Brick\Math\Internal\CalculatorRegistry::get(); echo get_class($calculator); // Possible outputs: // - Brick\Math\Internal\Calculator\GmpCalculator // - Brick\Math\Internal\Calculator\BcMathCalculator // - Brick\Math\Internal\Calculator\NativeCalculator ``` -------------------------------- ### Get the Sign of a BigNumber Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigNumber.md The `getSign()` method returns the mathematical sign of a number: -1 for negative, 0 for zero, and 1 for positive. It's essential for algorithms that depend on the sign of a value. ```php BigInteger::of(5)->getSign(); // 1 BigInteger::of(0)->getSign(); // 0 BigInteger::of(-5)->getSign(); // -1 ``` -------------------------------- ### BigDecimal Division with Scale and Rounding Source: https://github.com/brick/math/blob/main/README.md Shows how to divide BigDecimal numbers, requiring a scale and optionally a rounding mode when the result is not exact within the specified scale. ```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 ``` -------------------------------- ### Catching RoundingNecessaryException Source: https://github.com/brick/math/blob/main/_autodocs/errors.md Demonstrates how to catch RoundingNecessaryException and provide a valid rounding mode, such as RoundingMode::HalfUp, when an operation requires rounding. ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; use Brick\Math\Exception\RoundingNecessaryException; try { BigDecimal::of(1)->dividedBy(3, 2); // Requires rounding } catch (RoundingNecessaryException $e) { // Provide a rounding mode instead $result = BigDecimal::of(1)->dividedBy(3, 2, RoundingMode::HalfUp); } ``` -------------------------------- ### toBase() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Converts a BigInteger to its string representation in a specified base, ranging from 2 to 36. The output uses lowercase letters for bases greater than 10. ```APIDOC ## toBase() ### Description Converts this number to a string in a given base (2-36). ### Method ```php final public function toBase(int $base): string ``` ### Parameters #### Path Parameters - **base** (int) - Required - Base: 2 to 36 ### Return Type `string` — Number as string in given base (lowercase for hex/bases > 10). ### Throws - `InvalidArgumentException` — If base is outside 2-36 ### Examples ```php $num = BigInteger::of(255); $num->toBase(2); // '11111111' $num->toBase(16); // 'ff' $num->toBase(10); // '255' $num = BigInteger::of(1000); $num->toBase(36); // 'rs' ``` ``` -------------------------------- ### Get Integral Part of BigRational Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Retrieves the integral part of a BigRational number. This is the whole number part obtained by dividing the numerator by the denominator and truncating toward zero. For fractions less than 1, it returns 0. ```php BigRational::of('7/3')->getIntegralPart(); // 2 (since 7/3 = 2 + 1/3) BigRational::of('-7/3')->getIntegralPart(); // -2 (since -7/3 = -2 + (-1/3)) BigRational::of('1/3')->getIntegralPart(); // 0 BigRational::of('5/1')->getIntegralPart(); // 5 ``` -------------------------------- ### power() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Raises this number to an integer exponent, including negative exponents. The result is automatically simplified. ```APIDOC ## power() ### Description Raises this number to an integer exponent (including negative). ### Method `final public function power(int $exponent): BigRational` ### Parameters #### Path Parameters - **exponent** (int) - Yes - Integer exponent (can be negative) ### Return Type `BigRational` — Result of this^exponent, automatically simplified. ### Throws - `DivisionByZeroException` — If exponent is negative and this is zero ### Behavior - Positive exponent: multiply this by itself - Negative exponent: raise reciprocal to abs(exponent) - Zero exponent: always returns 1/1 ### Examples ```php BigRational::of('2/3')->power(2); // 4/9 BigRational::of('2/3')->power(3); // 8/27 BigRational::of('2/3')->power(-1); // 3/2 (reciprocal) BigRational::of('2/3')->power(-2); // 9/4 BigRational::of(5)->power(0); // 1/1 ``` ``` -------------------------------- ### Get Fractional Part of BigRational Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Retrieves the fractional part of a BigRational number. This is the result of subtracting the integral part from the rational number. The returned fraction will always have an absolute value less than 1, or be 0 if the number is an integer. ```php BigRational::of('7/3')->getFractionalPart(); // 1/3 (since 7/3 = 2 + 1/3) BigRational::of('-7/3')->getFractionalPart(); // -1/3 (since -7/3 = -2 + (-1/3)) BigRational::of('5/1')->getFractionalPart(); // 0/1 BigRational::of('1/3')->getFractionalPart(); // 1/3 ``` -------------------------------- ### Square Root Calculation with Different Rounding Modes Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Demonstrates calculating the integer square root of a BigInteger using various rounding modes: Down, Up, and HalfUp. ```php use Brick\Math\BigInteger; use Brick\Math\RoundingMode; $num = BigInteger::of(10); // Square root of 10 $num->sqrt(RoundingMode::Down); // 3 $num->sqrt(RoundingMode::Up); // 4 $num->sqrt(RoundingMode::HalfUp); // 3 ``` -------------------------------- ### Get cached BigRational instances for 0, 1, and 10 Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Use the `zero()`, `one()`, and `ten()` factory methods to retrieve cached instances of BigRational representing 0, 1, and 10 respectively. This is efficient for frequently used constant values. ```php use Brick\Math\BigRational; $zero = BigRational::zero(); $one = BigRational::one(); $ten = BigRational::ten(); ``` -------------------------------- ### BigDecimal Class Documentation Source: https://github.com/brick/math/blob/main/_autodocs/MANIFEST.txt Documentation for the BigDecimal class, handling arbitrary-precision decimal numbers with methods for precise arithmetic and scale manipulation. ```APIDOC ## BigDecimal Class ### Description Represents arbitrary-precision decimal numbers. Ensures precision in decimal arithmetic operations. ### Factory Methods - **of(value):** Creates a BigDecimal from a string, integer, or float. - **zero():** Returns a BigDecimal representing zero. - **one():** Returns a BigDecimal representing one. - **ten():** Returns a BigDecimal representing ten. ### Float Conversion - **fromFloatExact(float):** Creates a BigDecimal from a float, preserving exact value if possible. - **fromFloatShortest(float):** Creates a BigDecimal from a float using the shortest possible representation. ### Unscaled Value - **ofUnscaledValue(unscaledValue, scale):** Creates a BigDecimal from an unscaled value and a scale. ### Arithmetic Operations - **plus(other):** Adds another BigDecimal to this one. - **minus(other):** Subtracts another BigDecimal from this one. - **multipliedBy(other):** Multiplies this BigDecimal by another. - **dividedBy(other):** Divides this BigDecimal by another (returns BigNumber). - **dividedByExact(other):** Divides this BigDecimal by another, throws exception if remainder is non-zero. ### Division Breakdown - **quotient(other):** Returns the quotient of the division. - **remainder(other):** Returns the remainder of the division. - **quotientAndRemainder(other):** Returns an object containing both quotient and remainder. ### Power Operations - **power(exponent):** Raises this BigDecimal to a non-negative integer exponent. ### Root Operations - **sqrt():** Computes the square root of this BigDecimal. - **nthRoot(nth):** Computes the nth root of this BigDecimal. ### Scale Operations - **getScale():** Returns the scale of the BigDecimal. - **getUnscaledValue():** Returns the unscaled value of the BigDecimal. - **withScale(scale):** Returns a BigDecimal with the specified scale, rounding if necessary. - **strippedOfTrailingZeros():** Returns a BigDecimal with trailing zeros removed. ``` -------------------------------- ### BigNumber Class Documentation Source: https://github.com/brick/math/blob/main/_autodocs/MANIFEST.txt Documentation for the abstract base class BigNumber, including factory methods, comparison, sign/value, arithmetic, and conversion methods. ```APIDOC ## BigNumber Class ### Description Provides the base functionality for arbitrary-precision numbers. It serves as an abstract base class for BigInteger, BigDecimal, and BigRational. ### Factory Methods - **of(value):** Creates a BigNumber instance from a numeric value. - **ofNullable(value):** Creates a BigNumber instance from a numeric value, returning null if the input is null. - **min(a, b):** Returns the smaller of two BigNumber instances. - **max(a, b):** Returns the larger of two BigNumber instances. - **sum(a, b):** Returns the sum of two BigNumber instances. ### Comparison Methods - **isEqualTo(other):** Checks if this BigNumber is equal to another. - **isLessThan(other):** Checks if this BigNumber is less than another. - **isGreaterThan(other):** Checks if this BigNumber is greater than another. - **isLessThanOrEqualTo(other):** Checks if this BigNumber is less than or equal to another. - **isGreaterThanOrEqualTo(other):** Checks if this BigNumber is greater than or equal to another. ### Sign and Value Methods - **isZero():** Checks if this BigNumber is zero. - **isNegative():** Checks if this BigNumber is negative. - **getSign():** Returns the sign of this BigNumber (-1, 0, or 1). ### Arithmetic Operations - **abs():** Returns the absolute value of this BigNumber. - **negated():** Returns the negation of this BigNumber. - **clamp(min, max):** Clamps this BigNumber between a minimum and maximum value. ### Conversions - **toBigInteger():** Converts this BigNumber to a BigInteger. - **toBigDecimal():** Converts this BigNumber to a BigDecimal. - **toBigRational():** Converts this BigNumber to a BigRational. - **toInt():** Converts this BigNumber to a PHP integer (may lose precision). - **toFloat():** Converts this BigNumber to a PHP float (may lose precision). - **toString():** Converts this BigNumber to its string representation. ### Magic Methods - **__toString():** Alias for toString(). - **jsonSerialize():** Prepares the BigNumber for JSON serialization. ``` -------------------------------- ### Interface Compliance for Number Classes Source: https://github.com/brick/math/blob/main/_autodocs/configuration.md Demonstrates that all number classes implement JsonSerializable and Stringable interfaces. This code shows how to use these interfaces with type hints for function parameters. ```php use JsonSerializable; use Stringable; // All number classes implement interface MyNumber extends JsonSerializable, Stringable {} // Works with type hints function process(JsonSerializable $data): void { echo json_encode($data); } $num = BigInteger::of(42); process($num); // ✓ Accepted ``` -------------------------------- ### Usage in Division Operations Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Demonstrates how to use different RoundingMode options, including HalfEven, when performing division operations with BigDecimal. ```APIDOC ## Usage Examples ### In Division Operations ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; $dividend = BigDecimal::of(10); $divisor = BigDecimal::of(3); $scale = 2; // Different rounding modes for 10 / 3 $dividend->dividedBy($divisor, $scale, RoundingMode::Unnecessary); // throws RoundingNecessaryException $dividend->dividedBy($divisor, $scale, RoundingMode::Down); // 3.33 $dividend->dividedBy($divisor, $scale, RoundingMode::Up); // 3.34 $dividend->dividedBy($divisor, $scale, RoundingMode::HalfUp); // 3.33 $dividend->dividedBy($divisor, $scale, RoundingMode::Ceiling); // 3.34 $dividend->dividedBy($divisor, $scale, RoundingMode::Floor); // 3.33 ``` ``` -------------------------------- ### Raise a BigRational number to an integer power using power() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Use the power() method to raise the current BigRational to an integer exponent, which can be positive, negative, or zero. Negative exponents calculate the reciprocal raised to the absolute value of the exponent. Zero exponent always returns 1/1. Division by zero will occur if the exponent is negative and the base is zero. ```php BigRational::of('2/3')->power(2); // 4/9 BigRational::of('2/3')->power(3); // 8/27 BigRational::of('2/3')->power(-1); // 3/2 (reciprocal) BigRational::of('2/3')->power(-2); // 9/4 BigRational::of(5)->power(0); // 1/1 ``` -------------------------------- ### Currency Calculation with RoundingMode::HalfUp Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/RoundingMode.md Illustrates a currency calculation scenario where dividing a total bill among people requires careful rounding to ensure the sum of individual payments matches the total. Uses RoundingMode::HalfUp. ```php use Brick\Math\BigDecimal; use Brick\Math\RoundingMode; // Divide a bill equally among 3 people $total = BigDecimal::of('29.99'); $perPerson = $total->dividedBy(3, 2, RoundingMode::HalfUp); echo $perPerson; // 10.00 (each person pays) // But 3 × 10.00 = 30.00, not 29.99! // Need to round differently to match total ``` -------------------------------- ### power() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Raises the current BigInteger to a non-negative integer exponent. ```APIDOC ## power() ### Description Raises this number to a non-negative integer exponent. ### Method `public function power(int $exponent): BigInteger` ### Parameters #### Path Parameters - **exponent** (int) - Required - Exponent (non-negative) ### Return Type `BigInteger` — Result of this^exponent. ### Throws - `InvalidArgumentException` — If exponent < 0 ### Examples ```php BigInteger::of(2)->power(10); // 1024 BigInteger::of(10)->power(3); // 1000 BigInteger::of(5)->power(0); // 1 BigInteger::of(-2)->power(3); // -8 BigInteger::of(-2)->power(4); // 16 ``` ``` -------------------------------- ### BigInteger Quotient and Remainder Operations Source: https://github.com/brick/math/blob/main/README.md Provides methods to retrieve the quotient, remainder, or both simultaneously from a BigInteger division. ```php echo BigInteger::of(1000)->quotient(3); // 333 echo BigInteger::of(1000)->remainder(3); // 1 ``` ```php [$quotient, $remainder] = BigInteger::of(1000)->quotientAndRemainder(3); ``` -------------------------------- ### quotient() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigInteger.md Calculates the quotient of Euclidean division, truncated toward zero. ```APIDOC ## quotient() ### Description Returns the quotient of Euclidean division (truncated toward zero). ### Method `public function quotient(BigNumber|int|string $that): BigInteger` ### Parameters #### Path Parameters - **that** (BigNumber|int|string) - Required - Divisor ### Return Type `BigInteger` — The quotient. ### Throws - `DivisionByZeroException` — If divisor is zero - `MathException` — If value is invalid ### Behavior Division truncates toward zero (different from `//` operator which rounds floor). ### Examples ```php BigInteger::of(7)->quotient(3); // 2 BigInteger::of(7)->quotient(-3); // -2 BigInteger::of(-7)->quotient(3); // -2 BigInteger::of(-7)->quotient(-3); // 2 ``` ``` -------------------------------- ### plus() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Returns the sum of this and another rational number. The result is automatically simplified to its lowest terms. ```APIDOC ## plus() ### Description Returns the sum of this and another rational number. ### Method `final public function plus(BigNumber|int|string $that): BigRational` ### Parameters #### Path Parameters - **that** (BigNumber|int|string) - Yes - Number to add (converted to BigRational) ### Return Type `BigRational` — Sum, automatically simplified to lowest terms. ### Throws - `MathException` — If value is invalid or not convertible ### Examples ```php $a = BigRational::of('1/3'); $a->plus('1/6'); // 1/2 (simplified from 3/6) $a->plus(BigRational::of('2/3')); // 1/1 (simplified from 3/3) $a->plus(2); // 7/3 ``` ``` -------------------------------- ### BigInteger Bitwise Operations Source: https://github.com/brick/math/blob/main/README.md Illustrates the bitwise AND, OR, XOR, NOT, and bit shifting operations supported by BigInteger. ```php // and(), or(), xor(), not() // shiftedLeft(), shiftedRight() ``` -------------------------------- ### toString() Source: https://github.com/brick/math/blob/main/_autodocs/api-reference/BigRational.md Returns the string representation of the rational number in the format 'numerator/denominator'. ```APIDOC ## toString() ### Description Returns the string representation as `numerator/denominator`. ### Method `toString(): string` ### Return Type `string` — Format: "num/denom" (no space). ### Examples ```php BigRational::of('2/3')->toString(); // '2/3' BigRational::of(5)->toString(); // '5/1' BigRational::of('-1/2')->toString(); // '-1/2' BigRational::of(0)->toString(); // '0/1' ``` ``` -------------------------------- ### Avoid DivisionByZeroException by Checking for Zero Source: https://github.com/brick/math/blob/main/_autodocs/errors.md Before dividing, check if the divisor is zero using the `isZero()` method to prevent `DivisionByZeroException`. This is crucial when user input or external data determines the divisor. ```php $divisor = BigInteger::of(getUserInput()); if ($divisor->isZero()) { echo "Cannot divide by zero"; } else { $result = BigInteger::of(100)->dividedBy($divisor); } ```