A PHP 5.3+ mathematics library, providing functionality for large numbers

Related tags

Numbers math
Overview

Moontoast Math Library

Build Status

Moontoast\Math is useful for working with integers that are larger than (or may become larger than, through mathematical computations) PHP's max integer value for a given system. On 64-bit systems, this number is 9223372036854775807. On 32-bit systems, it is 2147483647. When overflowing this boundary, PHP turns the number into a float, reducing precision (see the PHP manual entry for Integers).

Moontoast\Math provides an easy-to-use wrapper around the bcmath extension, allowing one to perform mathematical calculations on numeric strings, going well outside the integer range of the system and maintaining arbitrary precision for more precise calculations.

See the docs/ directory for generated API documentation.

Moontoast\Math requires PHP 5.3+ and the bcmath extension.

Installation

The preferred method of installation is via Packagist, as this provides the PSR-0 autoloader functionality. The following composer.json will download and install the latest version of the Moontoast\Math library into your project:

{
    "require": {
        "moontoast/math": "*"
    }
}

Examples

$bn = new \Moontoast\Math\BigNumber('9,223,372,036,854,775,808');
$bn->multiply(35);

var_dump($bn->getValue());
var_dump($bn->convertToBase(16));

This produces the following output:

string(21) "322818021289917153280"
string(18) "118000000000000000"

You might want to use BigNumber to work with a UUID, which is an unsigned 128-bit integer. For example:

$uuid = \Moontoast\Math\BigNumber::convertToBase10('ff6f8cb0c57d11e19b210800200c9a66', 16);

This utility converts the UUID from hexadecimal (base 16) representation to a string representation of the unsigned 128-bit integer in decimal (base 10). You may now create a BigNumber object with it to perform calculations, if you wish.

$bn = new \Moontoast\Math\BigNumber($uuid);
echo $bn; // 339532337419071774305803111643925486182

License

Copyright © 2013 Moontoast, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Comments
  • PHP 7.0: invalid numeric literal error due to invalid octal number

    PHP 7.0: invalid numeric literal error due to invalid octal number

    When you try to run composer install on a PHP 7.0.0 (stable) machine, you will get an error along the lines of

    Parse error: Invalid numeric literal in /home/vagrant/git/math/tests/Moontoast/Math/BigNumberTest.php on line 622
    

    Having a look at line 622, you'll see this:

    $convertValues = array(10, 27, 39, 039, 0x5F, '10', '27', '39', '5F', '5f', '3XYZ', '3xyz', '5f$@');
    

    and using Google for above error you immediately find PHP bug #70193 and there's this explanation:

    Numbers starting with 0 are octal literals. 08 is not a valid octal literal, so you get an error now. Previously it was silently treated like 0.

    which really makes sense.

    Obviously, the problem is the "octal" (as interpreted by PHP) value 039 which is in fact not octal (9 isn't a valid octal digit). I changed 039 and -039 to 037 and -037, respectively, and now there are now more syntax errors and the tests pass.

    I hope you didn't choose 039 because it might produce an unexpected result when converting bases and changing it to 037 doesn't somehow make it "easier" to pass the tests.

    What do you think?

    (Note: the "bump" commit was to trigger Travis CI)

    opened by limenet 3
  • Test enhancement

    Test enhancement

    Changed log

    • Add php-7.2, php-5.3 and php-nightly tests.
    • Allow the php-nightly and hhvm to be failed in Travis CI build.
    • Use the psr-4 to load classes automatically.
    • Use the class-based PHPUnit namespace to be compatible with the latest PHPUnit version.
    • To avoid the Invalid numeric literal syntax error in php-7.x version, it should change them to the string expression.
    • In testNegativeZero test method, the signum and isNegative are unexpected result in php-5.x and php-7.x. I think the assertion is correct in php-7.x, but the php-5.x does not. To avoid this issue, I remove that two assertions.
    opened by peter279k 2
  • php 7.0 unit tests fixes - correct octal numbers

    php 7.0 unit tests fixes - correct octal numbers

    Unit tests fail on php7 with the following error:

    PHP Parse error:  Invalid numeric literal in /home/alex/work/math/tests/Moontoast/Math/BigNumberTest.php on line 622
    
    opened by alex-vlasov 2
  • Ignore composer self-update failures.

    Ignore composer self-update failures.

    Made composer self-update optional, because a failure here would stop the build. This command is dependent from the uptime of "getcomposer.org" and only needed if the travis composer version is too old.

    opened by h4cc 0
  • Does it work well with floating point numbers too

    Does it work well with floating point numbers too

    I'm new the math calculations in PHP. But I noticed your library focused on BIG integers. What about deep floating point numbers? Can I use it to accurately calculate that? Or would I need to convert decimals to integers before using your library.

    opened by CMCDragonkai 2
  • Immutable BigNumber

    Immutable BigNumber

    Hello,

    I would like to use this library on the sonata-project, however the BigNumber class is mutable, I would like to introduce a new ImmutableBigNumber class.

    What do you think ?

    opened by rande 2
Owner
Moontoast
Moontoast
PHP version of Google's phone number handling library

libphonenumber for PHP What is it? A PHP library for parsing, formatting, storing and validating international phone numbers. This library is based on

Joshua Gigg 4.2k Jan 7, 2023
Library for converting units and sizes in PHP

php-conversion Library for converting units and sizes in PHP. Units supported Acceleration Angle Area Digital information Electric current Frequency F

Christoffer Niska 127 Dec 23, 2022
BigNum library for PHP compatible with bn.js

BigNum library for PHP Information This library provides a PHP Big Number API compatible with bn.js and is used in Fast PHP ECC library elliptic-php.

Simplito 16 Nov 13, 2022
Library for converting units and sizes in PHP

php-conversion Library for converting units and sizes in PHP. Units supported Acceleration Angle Area Digital information Electric current Frequency F

Christoffer Niska 122 Mar 16, 2021
Mark Rogoyski 2.2k Dec 29, 2022
Arbitrary-precision arithmetic library for PHP

Arbitrary-precision arithmetic library for PHP

Brick 1.4k Jan 1, 2023
Tensor is a library and extension that provides objects for scientific computing in PHP.

Tensor is a library and extension that provides objects for scientific computing in PHP. The multithreaded extension is especially suited for computing large sets of numbers. In some cases, the extension is 230X faster than the same operation in PHPland. Tensor is used by libraries such as Rubix ML to build and accelerate machine learning algorithms such as linear regression, dimensionality reduction, and neural networks.

Rubix 157 Jan 3, 2023
Library to parse, format and convert byte units

Byte Units This is a utility component for parsing, formatting, converting and manipulating byte units in various formats. Usage <?php // Bytes manip

Gabriele Lana 156 Dec 9, 2022
A library for handling physical quantities and the units of measure in which they're represented.

PHP Units of Measure master: Introduction This is a PHP library for representing and converting physical units of measure. The utility of this library

Jonathan Hanson 21 Sep 28, 2022
Unit converter and calculator for php

Unit converter and calculator This library uses the awesome lisachenko/z-engine to allow mathematical operations on objects, allowing to do stuff like

Dominik Chrástecký 8 Apr 8, 2022
Advanced Mathematics Library for PHP (port of Numbers.js)

Numbers.php Numbers.php - an advanced mathematics toolkit for PHP >= 5.3. It is a port of Numbers.js - same toolkit for JavaScript. There is a version

null 159 Jul 24, 2022
Staggered import of large and very large MySQL Dumps even through the web servers with hard runtime limit and those in safe mode.

Staggered import of large and very large MySQL Dumps (like phpMyAdmin dumps) even through the web servers with hard runtime limit and those in safe mode. | Persian Translation Version

Amir Shokri 5 Jan 8, 2022
PHP library providing retry functionality with multiple backoff strategies and jitter support

PHP Backoff Easily wrap your code with retry functionality. This library provides: 4 backoff strategies (plus the ability to use your own) Optional ji

Signature Tech Studio 145 Dec 21, 2022
Tiny PHP library providing retry functionality with multiple backoff strategies and jitter support

JBZoo / Retry 4 retry strategies (plus the ability to use your own) Optional jitter / randomness to spread out retries and minimize collisions Wait ti

JBZoo Toolbox 6 Dec 19, 2022
Providing some testing functionality for Laravel

Laravel TestBench Laravel TestBench was created by, and is maintained by Graham Campbell, and provides some testing functionality for Laravel. It util

Graham Campbell 50 Dec 20, 2022
PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Manufacturing Industry, Phone numbers & Zipcodes for many countries

IsoCodes PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Book Industry, Phone numbers & Zipcodes

Ronan Guilloux 767 Jan 2, 2023
A small PHP library to generate YouTube-like ids from numbers.

A small PHP library to generate YouTube-like ids from numbers. Use it when you don't want to expose your database ids to the user.

Vincent Klaiber 4.9k Dec 30, 2022
A small PHP library for validating VAT identification numbers (VATINs).

VATIN A small PHP library for validating VAT identification numbers (VATINs). Installation This library is available on Packagist: $ composer require

David de Boer 128 Oct 27, 2022
PHP library to validate and format license plate numbers.

License plate validator and formatter CI Status Lint Coverage Tests This library can be used to validate and format license plate numbers. Countries s

Automex.website 1 Oct 19, 2022
A tool for creating configurable dumps of large MySQL-databases.

slimdump slimdump is a little tool to help you create configurable dumps of large MySQL-databases. It works off one or several configuration files. Fo

webfactory GmbH 176 Dec 26, 2022