Mathematical questions and applications always trigger me. Recently I just finished a book by Stephen Hawking “God Created The Integers” and being able to “talk” to those great mathematicians in history thrills me. This is the main reason I decided to write about this topic.
In this article, we will review the PHP capability to provide arbitrary precision number calculation / big integer calculation by reviewing 3 PHP modules: GMP, BC Math and php-bignumbers. We will demonstrate two real-world examples to see the powers/limitations of each. The first one will be calculating PI to arbitrary precision – well, for the sake of the article, we will restrict the precision, say, to 1000 digits; the second will be a simple demonstration on RSA encryption/decryption.
Let’s get started.
Preparation
To get the GMP PHP module, simply issue the following command in your terminal on any Unix system (or install it manually if on Windows – but please use Vagrant!):
sudo apt-get install php5-gmp
php-bignumbers is distributed via Composer. Create a composer.json file and run php composer.phar install after adding the requirement. The php-bignumbers Github site has the detailed information to how to write the composer.json file.
BC is usually pre-installed and enabled.
After installation, we can test that all are working fine by writing a simple PHP script and running it in the terminal:
<?php
// Below is to test php-bignumber lib
require_once 'vendor/autoload.php'; // Required for autoload
use \Litipk\BigNumbers\Decimal as Decimal;
$one = Decimal::fromInteger(1);
$two= Decimal::fromInteger(2);
$three=Decimal::fromInteger(3);
$seven = Decimal::fromString('7.0');
$a=$one->div($seven, 100); // Should display something like 0.142857142857 .....and the last digit is 9 in consideration of rounding up the 101th digit.
$b=$two->div($seven, 100);
$c=$three->div($seven, 100);
echo ($c
Truncated by Planet PHP, read more at the original (another 19240 bytes)
more
{ 0 comments... » Arbitrary Precision and Big Numbers in PHP read them below or add one }
Post a Comment