jchamberlain jchamberlain - 1 year ago 109
PHP Question

PHP: How to raise number to (tiny) fractional exponent?

I'm doing a calculation in PHP using

, and need to raise
by a fractional exponent. Unfortunately,
only accepts integer exponents. The exponent is typically higher precision than a float will allow, so normal arithmetic functions won't cut it.

For example:

$e = exp(1);
$pow = "0.000000000000000000108420217248550443400745280086994171142578125";
$result = bcpow($e, $pow);

Result is
with the error, "bc math warning: non-zero scale in exponent".

Is there another function I can use instead of

Answer Source

Your best bet is probably to use the Taylor series expansion. As you noted, PHP's bcpow is limited to raising to integer exponentiation.

So what you can do is roll your own bc factorial function and use the wiki page to implement a Taylor series expansion of the exponential function.

function bcfac($num) { 
    if ($num==0) return 1;
    $result = '1';
    for ( ; $num > 0; $num--)
        $result = bcmul($result,$num);
    return $result;
$mysum = '0';
for ($i=0; $i<300; $i++) {
    $mysum = bcadd($mysum, bcdiv(bcpow($pow,$i), bcfac($i)) );
print $mysum;

Obviously, the $i<300 is an approximation for infinity... You can change it to suit your performance needs.

With $i=20, I got


This is comforting since that small of an exponent should yield something really close to 1.0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download