working version (checked) of below code is
<?php
// see bccomp for this code (signed and unsigned zero!)
function bccomp_zero($amount) {
return bccomp($amount, (@$amount{0}=="-"?'-':'').'0.0');
}
// arbitrary precision function (x^n)/(n)!
function bcpowfact($x, $n) {
if (bccomp_zero($n) == 0) return '1';
if (bccomp($n, '1') == 0) return $x;
$a = $x; // 1st step: a *= x / 1
$i = $n;
while (bccomp($i, '1') == 1) {
// ith step: a *= x / i
$a = bcmul($a, bcdiv($x, $i));
$i = bcsub($i, '1'); // bc idiom for $i--
}
return $a;
}
// arbitrary precision exp() function
function bcexp($x, $digits) {
$sum = $prev_sum = '0.0';
$error = '0.'.str_repeat('0', $digits-1).'1'; // 0.1*10^-k
$n = '0.0';
do {
$prev_sum = $sum;
$sum = bcadd($sum, bcpowfact($x, $n));
$n = bcadd($n, '1'); // bc idiom for $n++
} while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
return $sum;
}
?>
exp
(PHP 4, PHP 5)
exp — e の累乗を計算する
説明
float exp
( float $arg
)
e を arg 乗した値を返します。
注意: 'e' は自然対数の底で、およそ 2.718282 です。
パラメータ
- arg
-
処理する引数。
返り値
'e' の arg 乗を返します。
例
例1 exp() の例
<?php
echo exp(12) . "\n";
echo exp(5.7);
?>
上の例の出力は以下となります。
1.6275E+005 298.87
exp
konrad
25-Jan-2007 08:13
25-Jan-2007 08:13
boards at gmail dot com
27-Apr-2006 02:18
27-Apr-2006 02:18
Note regarding the mathematical function exp(x):
To continue accuracy of the exponential function to an infinite amount of decimal places, one would use the power series definition for exp(x).
(in LaTeX form:)
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}
So, to do that in PHP (using BC math):
<?php
// arbitrary precision function (x^n)/(n)!
function bcpowfact($x, $n) {
if (bccomp($n, '0') == 0) return '1.0';
if (bccomp($n, '1') == 1) return $x;
$a = $x; // nth step: a *= x / 1
$i = $n;
while (bccomp($i, '1') == 1) {
// ith step: a *= x / i
$a = bcmul($a, bcdiv($x, $i));
$i = bcsub($i, '1'); // bc idiom for $i--
}
return $a;
}
// arbitrary precision exp() function
function bcexp($x, $decimal_places) {
$sum = $prev_sum = '0.0';
$error = bcdiv(bcpow('10', '-'.$decimal_places), 10); // 0.1*10^-k
$n = '0';
do {
$prev_sum = $sum;
$sum = bcadd($sum, bcpowfact($x, $n));
}
while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
return $sum;
}
?>
info at teddycaddy dot com
16-Sep-2004 10:55
16-Sep-2004 10:55
This only returns the first 51 digits after the decimal point.