VII. BC math 高精度数学函数


PHP 为任意精度数学计算提供了二进制计算器(Binary Calculator),它支持任意大小和精度的数字,以字符串形式描述。


自 PHP 4.0.4 以来,libbcmath 都绑定在 PHP 内部。本扩展不需要其它外部库的支持。


本类函数仅在 PHP 编译时配置了 --enable-bcmath 时可用。在 PHP 3 中,本类函数仅在 PHP 编译时没有配置 --disable-bcmath 时可用。

PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。


这些函数的行为受 php.ini 的影响。

表格 1. BC 数学库配置选项

bcmath.scale"0"PHP_INI_ALL自 PHP 5.0.0 起可用。
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G


bcmath.scale integer

所有 bcmath 函数中十进制数字的数目。参见 bcscale()





bcadd -- Add two arbitrary precision numbers
bccomp -- Compare two arbitrary precision numbers
bcdiv -- Divide two arbitrary precision numbers
bcmod --  Get modulus of an arbitrary precision number
bcmul -- Multiply two arbitrary precision number
bcpow --  Raise an arbitrary precision number to another
bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus
bcscale --  Set default scale parameter for all bc math functions
bcsqrt --  Get the square root of an arbitrary precision number
bcsub --  Subtract one arbitrary precision number from another

add a note add a note User Contributed Notes
marcus at synchromedia dot co dot uk
10-Aug-2006 12:17
Oops, first posting contained wrong code... sorry.
An amendment to the entry by pulstar at mail dot com - the digits() function can be made much faster (remove the line breaks from the big string, and make sure you don't miss any characters!):

function digits2($base) {
   if($base < 64) {
       return substr('0123456789abcdefghijklmnopqrstuvwxyz
   } else {
       return substr("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd
\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", 0, $base);

in my benchmarks, this is around 150x faster for 256 digits
stonehew ut gm a il det com
25-Nov-2004 01:31
Like any other bc function, you can't trust the last couple of digits, but everything else seems to check out.  If you want to use this for anything important, you may want to verify this against other sources of pi before use.  This function calculates 100 decimal places of pi in 329 iterations -- not exactly fast (each iteration calls the factorial function, from below, twice), so I try to avoid calling it more than once.

//arbitrary precision pi approximator
//author tom boothby
//free for any use

function bcpi() {

bccomp($or,$r)) {
$r = bcadd($r,bcdiv(bcmul(bcpow(bcfact($i),2),


stonehew et g m a i l dut com
24-Nov-2004 03:20
I hacked these taylor expansions up to make diagrams for some physics homework.  I don't think you'll be wanting to do any real science with PHP... but what the hell, why not?  I plan to implement either a spigot algorithm or something similar to generate pi in the near future.

// arbitrary precision sin and cosine functions
// author tom boothby
// free for any use

function bcfact($n) {
$r = $n--;
$n>1) $r=bcmul($r,$n--);

bcsin($a) {
$or= $a;
$r = bcsub($a,bcdiv(bcpow($a,3),6));
$i = 2;
bccomp($or,$r)) {
$i%2) {
0$r = bcadd($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
$r = bcsub($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;

bccos($a) {
$or= $a;
$r = bcsub(1,bcdiv(bcpow($a,2),2));
$i = 2;
bccomp($or,$r)) {
$i%2) {
0$r = bcadd($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
$r = bcsub($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;

Diabolos at GMail dot com
29-Oct-2004 02:42
Here's a function to compute the natural exponential function in arbitrary precision using the basic bcMath arithmetic operations.

To compute the exponential function of 1.7 to 36 decimals:

$y = bcExp("1.7", 36);

The result:

would be returned in variable $y

In practice, the last couple of digits may be inaccurate due to small rounding errors.  If you require a specific degree of precision, always compute 3-4 decimals beyond the required precision.

The program code for the natural exponential function is:

  Function bcExp($xArg, $NumDecimals)

   $x = Trim($xArg);

   $PrevSum  = $x - 1;
   $CurrTerm = 1;
   $CurrSum  = bcAdd("1", $x, $NumDecimals);
   $n        = 1;

   While (bcComp($CurrSum, $PrevSum, $NumDecimals))

   $PrevSum  = $CurrSum;
   $CurrTerm = bcDiv(bcMul($CurrTerm, $x, $NumDecimals), $n + 1, $NumDecimals);
   $CurrSum  = bcAdd($CurrSum, $CurrTerm, $NumDecimals);


   Return $CurrSum;
robert at scabserver dot com
04-Jun-2004 12:58
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandom

I know this is a *nix only solution, but I figured that it might come in handy to someone else.

The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.

function bcrand($size)
$filename = "/dev/urandom";
$handle = fopen($filename, "r");
$bin_urand = fread($handle, ceil($size/8.0));
$mask = (($size % 8 < 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));
$binmask = pack("H*", $mask);
$binrand = $binmask & $bin_urand;
$hexnumber = unpack("H*", $binrand);
$hexnumber = $hexnumber[''];
$numlength = strlen($hexnumber);
$decnumber = 0;
$x = 1; $x <= $numlength; $x++)
$place = $numlength - $x;
$operand = hexdec(substr($hexnumber,$place,1));
$exponent = bcpow(16,$x-1);
$decValue = bcmul($operand, $exponent);
$decnumber = bcadd($decValue, $decnumber);
pulstar at mail dot com
16-Apr-2003 08:12
A little comment for the simplified example above: you can do base converting without BCMath functions using only math operators, but you will not able to manage very large values or work with strings to compress or scramble data. If you have BCMath installed in your system it worth use it for this.
oliver at summertime dot net
02-Mar-2003 02:12
A simplier Version of the Script above:

function dec2base($dec, $digits) {
 $value = "";
 $base  = strlen($digits);
 while($dec>$base-1) {
  $rest = $dec % $base;
  $dec  = $dec / $base;
  $value = $digits[$rest].$value;
 $value = $digits[intval($dec)].$value;
 return (string) $value;

function base2dec($value, $digits) {
 $value = strtoupper($value);
 $base  = strlen($digits);
 $size  = strlen($value);
 $dec  = '0';
 for ($loop = 0; $loop<$size; $loop++) {
  $element = strpos($digits,$value[$loop]);
  $power  = pow($base,$size-$loop-1);
  $dec    += $element * $power;
 return (string) $dec;

echo dec2base('1000', $digits);
pulstar at mail dot com
20-Sep-2002 10:23
A found a little fix to do in my base2dec() function:
The line "if($base<37) $value=strtolower($value);" should be removed if you want to specify another digits for your base conversions. Change it this way:

if(!$digits) {
if($base<37) {

Another example using these functions is to generate a key for a session, to name temporary files or something else:

srand((double) microtime()*1000000);

$mykey is a base64 value, which is a good key for passing thru an URL and also is shorter than a MD5 string (it will be allways 11 chars long). If you need something more secure, just scramble the 64 digits in the digits() function.

Well, I hope you enjoy it.

Edemilson Lima
pulstar at mail dot com
20-Sep-2002 11:27
A good use for BCMath functions:
The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa.

// convert a decimal value to any other base value
function dec2base($dec,$base,$digits=FALSE) {
   if($base<2 or $base>256) die("Invalid Base: ".$base);
   if(!$digits) $digits=digits($base);
   while($dec>$base-1) {
   return (string) $value;

// convert another base value to its decimal value
function base2dec($value,$base,$digits=FALSE) {
   if($base<2 or $base>256) die("Invalid Base: ".$base);
   if($base<37) $value=strtolower($value);
   if(!$digits) $digits=digits($base);
   for($loop=0;$loop<$size;$loop++) {
   return (string) $dec;

function digits($base) {
   if($base>64) {
       for($loop=0;$loop<256;$loop++) {
   } else {
       $digits ="0123456789abcdefghijklmnopqrstuvwxyz";
   return (string) $digits;

The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result.
benjcarson at digitaljunkies dot ca
08-Jul-2002 08:00
In addition to my last note, here are  a quick pair of functions to convert exponential notation values into bcmath-style number strings:

// exp2int converts numbers in the
// form "1.5e4" into strings
function exp2int($exp) {
  list($mantissa, $exponent) = spliti("e", $exp);
  list($int, $dec) = split("\.", $mantissa);
  bcscale ($dec);
  return bcmul($mantissa, bcpow("10", $exponent));

// float2exp converts floats into exponential notation
function float2exp($num) {

  if (0 == $num) { return "0E1";}
  list($int, $dec) = split("\.", $num);

  // Extract sign
  if ($int[0] == "+" || $int[0] == "-") {
   $sign = substr($int, 0,1);
   $int = substr($int, 1);

  if (strlen($int) <= 1) {  // abs($num) is less than 1
   for ($i=0; $dec[$i]=='0' && $i < strlen($dec); $i++);
     $exp = -$i-1;     
     $mantissa = substr($dec,$i,1).".".substr($dec,$i+1);                             
   } else { // abs($num) is greater than 1
   for ($i=0; $int[$i]=='0' && $i < strlen($int); $i++);
     $exp = strlen($int)-1 - $i;
     $mantissa = substr($int,$i,1).".".substr($int,$i+1).$dec;

  return ($sign . $mantissa . "E" . $exp);
benjcarson at digitaljunkies ca
08-Jul-2002 07:17
Note that bcmath doesn't seem to handle numbers in exponential notation (i.e. "1e4"), although PHP considers such a value a number.


$exp1 = "1E5";
$exp2 = "2E4";
$ans1 = bcadd($exp1, $exp2, 3);
$ans2 = $exp1 + exp2;
echo("bcadd: $exp1 + $exp2 = $ans1");
echo("php: $exp1 + $exp2 = $ans2");

// Output:
bcadd: 1E5 + 2E4 = 0.000
php: 1E5 + 2E4 = 120000

Just a gotcha if you're using passing PHP numbers into bcmath functions...