bcpow

(PHP 3, PHP 4, PHP 5)

bcpow --  Raise an arbitrary precision number to another

Description

string bcpow ( string x, string y [, int scale] )

Raise x to the power y. The optional scale can be used to set the number of digits after the decimal place in the result.

范例

例子 1. bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

参见

bcpowmod()bcsqrt().


add a note add a note User Contributed Notes
Robert Lozyniak
04-May-2006 12:13
I hate every living thing that ever lived, except for Ms. A.Sh.O. and maybe also Ms. C.D.F. I hate the person who posted the silly joke below my post, and I hate myself immeasurably more.

That having been said:

This function takes arbitrary integers as exponents:

<?php

function bcpowislame($base,$exp,$scale) {
// I take arbitrary integers as exponents
// Remember, I take ONLY integers as exponents!
// bcpow is lame; I am a substitute
$wexp=bcadd($exp,'0',0);
if (
bccomp($exp,$wexp)) return false;
$wbase=$base; $wscale=$scale+strlen($wexp)+3; // the 3 is arbitrary
if ($wexp{0}=='-')
  {
$wbase=bcdiv('1',$wbase,$wscale); $wexp=bcsub('0',$wexp,0);}
if (
$wexp=='0') return bcadd('1','0',$scale);
$scr='1'; $scrm=$wbase; $loop=true;
while (
$loop) {
if (
bcmod($wexp,'2')=='1') $scr=bcmul($scr,$scrm,$wscale);
if (
bccomp($wexp,'1')==0) $loop=false;
else {
$scrm=bcmul($scrm,$scrm,$wscale); $wexp=bcdiv($wexp,'2',0);}}
return
bcadd('0',$scr,$scale); }

?>

I also hate my interpreter for not letting this work on negative exponents.
This seems to work great on positive exponents though.
12-Feb-2005 05:58
Well, if bcpow has limits, then this should work:
<?php
function bcpow_($num, $power) {
  
$awnser = "1";
   while (
$power) {
      
$awnser = bcmul($awnser, $num, 100);
      
$power = bcsub($power, "1");
   }
   return
rtrim($awnser, '0.');
}
?>
Just that $power cannot have decimal digits in it.
Michael Bailey (jinxidoru at byu dot net)
10-Aug-2004 08:42
bcpow() only supports exponents less than or equal to 2^31-1.  Also, bcpow() does not support decimal numbers.  If you have scale set to 0, then the exponent is converted to an interger; otherwise an error is generated.

--
Michael Bailey
http://www.jinxidoru.com