Top Related Projects
PHP implementation of Fowler's Money pattern.
PHP Secure Communications Library
Powerful modern math library for PHP: Features descriptive statistics and regressions; Continuous and discrete probability distributions; Linear algebra with matrices and vectors, Numerical analysis; special mathematical functions; Algebra
Quick Overview
Brick/Math is a PHP library that provides arbitrary-precision arithmetic for integers and decimals. It offers a robust set of mathematical operations and functions, allowing developers to perform precise calculations without the limitations of native PHP numeric types.
Pros
- Supports arbitrary-precision arithmetic for both integers and decimals
- Provides a comprehensive set of mathematical operations and functions
- Implements immutable value objects, ensuring data integrity
- Offers a user-friendly API with method chaining
Cons
- May have performance overhead compared to native PHP arithmetic operations
- Requires additional memory for large numbers or complex calculations
- Learning curve for developers unfamiliar with arbitrary-precision arithmetic concepts
- Limited support for advanced mathematical operations compared to specialized scientific libraries
Code Examples
Creating and performing basic operations:
use Brick\Math\BigInteger;
use Brick\Math\BigDecimal;
$a = BigInteger::of(123456789);
$b = BigInteger::of(987654321);
$sum = $a->plus($b);
echo $sum; // Output: 1111111110
Performing complex calculations:
use Brick\Math\BigDecimal;
$pi = BigDecimal::of('3.14159265358979323846');
$radius = BigDecimal::of(10);
$area = $pi->multipliedBy($radius->power(2));
echo $area->toScale(4); // Output: 314.1593
Working with fractions:
use Brick\Math\BigRational;
$a = BigRational::of('1/3');
$b = BigRational::of('1/6');
$sum = $a->plus($b);
echo $sum; // Output: 1/2
echo $sum->toFloat(); // Output: 0.5
Getting Started
To use Brick/Math in your PHP project, follow these steps:
-
Install the library using Composer:
composer require brick/math
-
Include the Composer autoloader in your PHP script:
require 'vendor/autoload.php';
-
Use the library in your code:
use Brick\Math\BigInteger; use Brick\Math\BigDecimal; use Brick\Math\BigRational; $result = BigInteger::of(42)->multipliedBy(10); echo $result; // Output: 420
Competitor Comparisons
PHP implementation of Fowler's Money pattern.
Pros of Money
- Specialized for handling monetary values and currency conversions
- Provides a more comprehensive set of money-related operations
- Includes built-in formatting and localization features
Cons of Money
- Limited to monetary calculations, less versatile for general mathematical operations
- May have a steeper learning curve for users not familiar with money-specific concepts
- Potentially slower performance for simple arithmetic operations
Code Comparison
Money:
use Money\Money;
$fiveDollars = Money::USD(500);
$tenDollars = Money::USD(1000);
$result = $fiveDollars->add($tenDollars);
Math:
use Brick\Math\BigDecimal;
$fiveDollars = BigDecimal::of('5.00');
$tenDollars = BigDecimal::of('10.00');
$result = $fiveDollars->plus($tenDollars);
Summary
Money is tailored for financial applications, offering currency-aware operations and formatting. Math provides a more general-purpose mathematical library with support for arbitrary-precision arithmetic. Choose Money for projects focused on monetary calculations and currency handling, while Math is better suited for broader mathematical operations and scenarios requiring high precision across various numeric types.
PHP Secure Communications Library
Pros of phpseclib
- Broader functionality, including cryptography and network protocols
- More mature project with a longer history and larger community
- Extensive documentation and examples
Cons of phpseclib
- Larger library size, potentially impacting performance
- May be overkill for projects only needing basic math operations
- Steeper learning curve due to its comprehensive feature set
Code Comparison
phpseclib (BigInteger class):
use phpseclib3\Math\BigInteger;
$a = new BigInteger('1234567890');
$b = new BigInteger('9876543210');
$result = $a->multiply($b);
brick/math (BigInteger class):
use Brick\Math\BigInteger;
$a = BigInteger::of('1234567890');
$b = BigInteger::of('9876543210');
$result = $a->multipliedBy($b);
Both libraries provide similar functionality for big integer operations, but phpseclib offers a wider range of features beyond mathematics. brick/math focuses solely on mathematical operations, making it more lightweight and potentially easier to use for projects with specific math-related needs.
Powerful modern math library for PHP: Features descriptive statistics and regressions; Continuous and discrete probability distributions; Linear algebra with matrices and vectors, Numerical analysis; special mathematical functions; Algebra
Pros of math-php
- Offers a wider range of mathematical functions and operations
- Includes statistical and probability functions
- Provides more advanced numerical methods and algorithms
Cons of math-php
- May have a steeper learning curve due to its extensive feature set
- Potentially slower performance for basic arithmetic operations
- Larger codebase, which could increase project size and complexity
Code Comparison
math-php:
use MathPHP\NumberTheory\Integer;
$primes = Integer::generatePrimes(100);
$lcm = Integer::lcm(12, 18);
$gcd = Integer::gcd(48, 18);
brick/math:
use Brick\Math\BigInteger;
$a = BigInteger::of(12);
$b = BigInteger::of(18);
$lcm = $a->lcm($b);
$gcd = $a->gcd($b);
math-php offers more specialized number theory functions out of the box, while brick/math focuses on basic arithmetic operations with arbitrary precision. math-php provides a dedicated class for integer operations, whereas brick/math uses a more general BigInteger class for various integer-related calculations.
Both libraries have their strengths, with math-php offering a broader range of mathematical functions and brick/math providing a simpler API for basic arithmetic operations with large numbers.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Brick\Math
A PHP library to work with arbitrary precision numbers.
Installation
This library is installable via Composer:
composer require brick/math
Requirements
This library requires PHP 8.1 or later.
For PHP 8.0 compatibility, you can use version 0.11
. For PHP 7.4, you can use version 0.10
. For PHP 7.1, 7.2 & 7.3, you can use version 0.9
. Note that these PHP versions are EOL and not supported anymore. If you're still using one of these PHP versions, you should consider upgrading as soon as possible.
Although the library can work seamlessly on any PHP installation, it is highly recommended that you install the GMP or BCMath extension to speed up calculations. The fastest available calculator implementation will be automatically selected at runtime.
Project status & release process
While this library is still under development, it is well tested and considered stable enough to use in production environments.
The current releases are numbered 0.x.y
. When a non-breaking change is introduced (adding new methods, optimizing
existing code, etc.), y
is incremented.
When a breaking change is introduced, a new 0.x
version cycle is always started.
It is therefore safe to lock your project to a given release cycle, such as ^0.12
.
If you need to upgrade to a newer release cycle, check the release history
for a list of changes introduced by each further 0.x.0
version.
Package contents
This library provides the following public classes in the Brick\Math
namespace:
- BigNumber: base class for
BigInteger
,BigDecimal
andBigRational
- BigInteger: represents an arbitrary-precision integer number.
- BigDecimal: represents an arbitrary-precision decimal number.
- BigRational: represents an arbitrary-precision rational number (fraction).
- RoundingMode: enum representing all available rounding modes.
And the following exceptions in the Brick\Math\Exception
namespace:
- MathException: base class for all exceptions
- DivisionByZeroException: thrown when a division by zero occurs
- IntegerOverflowException: thrown when attempting to convert a too large
BigInteger
toint
- NumberFormatException: thrown when parsing a number string in an invalid format
- RoundingNecessaryException: thrown when the result of the operation cannot be represented without explicit rounding
- NegativeNumberException: thrown when attempting to calculate the square root of a negative number
Overview
Instantiation
The constructors of the classes are not public, you must use a factory method to obtain an instance.
All classes provide an of()
factory method that accepts any of the following types:
BigNumber
instancesint
numbersfloat
numbersstring
representations of integer, decimal and rational numbers
Example:
BigInteger::of(123546);
BigInteger::of('9999999999999999999999999999999999999999999');
BigDecimal::of(1.2);
BigDecimal::of('9.99999999999999999999999999999999999999999999');
BigRational::of('2/3');
BigRational::of('1.1'); // 11/10
Note that all of()
methods accept all the representations above, as long as it can be safely converted to
the current type:
BigInteger::of('1.00'); // 1
BigInteger::of('1.01'); // RoundingNecessaryException
BigDecimal::of('1/8'); // 0.125
BigDecimal::of('1/3'); // RoundingNecessaryException
Note about native integers: instantiating from an int
is safe as long as you don't exceed the maximum
value for your platform (PHP_INT_MAX
), in which case it would be transparently converted to float
by PHP without
notice, and could result in a loss of information. In doubt, prefer instantiating from a string
, which supports
an unlimited numbers of digits:
echo BigInteger::of(999999999999999999999); // 1000000000000000000000
echo BigInteger::of('999999999999999999999'); // 999999999999999999999
Note about floating-point values: instantiating from a float
might be unsafe, as floating-point values are
imprecise by design, and could result in a loss of information. Always prefer instantiating from a string
, which
supports an unlimited number of digits:
echo BigDecimal::of(1.99999999999999999999); // 2
echo BigDecimal::of('1.99999999999999999999'); // 1.99999999999999999999
Immutability & chaining
The BigInteger
, BigDecimal
and BigRational
classes are immutable: their value never changes,
so that they can be safely passed around. All methods that return a BigInteger
, BigDecimal
or BigRational
return a new object, leaving the original object unaffected:
$ten = BigInteger::of(10);
echo $ten->plus(5); // 15
echo $ten->multipliedBy(3); // 30
The methods can be chained for better readability:
echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45
Parameter types
All methods that accept a number: plus()
, minus()
, multipliedBy()
, etc. accept the same types as of()
.
For example, given the following number:
$integer = BigInteger::of(123);
The following lines are equivalent:
$integer->multipliedBy(123);
$integer->multipliedBy('123');
$integer->multipliedBy($integer);
Just like of()
, other types of BigNumber
are acceptable, as long as they can be safely converted to the current type:
echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.0')); // 4
echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.5')); // RoundingNecessaryException
echo BigDecimal::of(2.5)->multipliedBy(BigInteger::of(2)); // 5.0
Division & rounding
BigInteger
By default, dividing a BigInteger
returns the exact result of the division, or throws an exception if the remainder
of the division is not zero:
echo BigInteger::of(999)->dividedBy(3); // 333
echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException
You can pass an optional rounding mode to round the result, if necessary:
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::DOWN); // 333
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::UP); // 334
If you're into quotients and remainders, there are methods for this, too:
echo BigInteger::of(1000)->quotient(3); // 333
echo BigInteger::of(1000)->remainder(3); // 1
You can even get both at the same time:
[$quotient, $remainder] = BigInteger::of(1000)->quotientAndRemainder(3);
BigDecimal
Dividing a BigDecimal
always requires a scale to be specified. If the exact result of the division does not fit in
the given scale, a rounding mode must be provided.
echo BigDecimal::of(1)->dividedBy('8', 3); // 0.125
echo BigDecimal::of(1)->dividedBy('8', 2); // RoundingNecessaryException
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HALF_DOWN); // 0.12
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HALF_UP); // 0.13
If you know that the division yields a finite number of decimals places, you can use exactlyDividedBy()
, which will
automatically compute the required scale to fit the result, or throw an exception if the division yields an infinite
repeating decimal:
echo BigDecimal::of(1)->exactlyDividedBy(256); // 0.00390625
echo BigDecimal::of(1)->exactlyDividedBy(11); // RoundingNecessaryException
BigRational
The result of the division of a BigRational
can always be represented exactly:
echo BigRational::of('123/456')->dividedBy('7'); // 123/3192
echo BigRational::of('123/456')->dividedBy('9/8'); // 984/4104
Bitwise operations
BigInteger
supports bitwise operations:
and()
or()
xor()
not()
and bit shifting:
shiftedLeft()
shiftedRight()
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.
Top Related Projects
PHP implementation of Fowler's Money pattern.
PHP Secure Communications Library
Powerful modern math library for PHP: Features descriptive statistics and regressions; Continuous and discrete probability distributions; Linear algebra with matrices and vectors, Numerical analysis; special mathematical functions; Algebra
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot