note 44985 added to ref.bc
| From: | emil dot muller at gmail dot com | Date: | Sun, 22 Aug 2004 14:45:04 +0000 |
| Subject: | note 44985 added to ref.bc | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-75115@lists.php.net to get a copy of this message | ||
bcscale(1000);
//Factorial
function fac($a) {
for ($b = 1; $a > 1; $a--) $b = bcmul($a,$b,0);
return $b;
}
//Exponential
//1+x+x^2/2+x^3/3!+...
function exp_($a,$b) {
$c = 1;
$d = 1;
$e = $a;
$f = 2;
do {
$c = bcadd($c,bcdiv($e,$d));
$e = bcmul($e,$a);
$d = bcmul($d,$f);
$f++;
$b--;
} while ($b > 0);
return $c;
}
//Natural logarithm
//log(x+1)=x-x^2/2+x^3/3-x^4/4+...
function log_($a,$b) {
if (bccomp($a,2) == 1) return bcmul(log10_($a,$b),bcsub(0,log_(0.1,$b)));
$a = bcsub($a,1);
$e = $a;
$c = $a;
$d = 2;
do {
$e = bcmul($e,$a);
if ($d & 1) $c = bcadd($c,bcdiv($e,$d));
else $c = bcsub($c,bcdiv($e,$d));
$d++;
$b--;
} while ($b > 0);
return $c;
}
//Base 10 logarithm
function log10_($a,$b) {
for ($c = 0; bccomp($a,1) == 1; $c++) $a = bcdiv($a,10);
return bcadd(bcdiv(log_($a,$b),bcsub(0,log_(0.1,$b))),$c);
}
//Gauss-Legendre
//log(n)/log(2) iterations for n digits
function pi_($c) {
$a = 1;
$b = bcdiv(1,bcsqrt(2));
$t = 0.25;
$x = 1;
do {
$y = $a;
$a = bcdiv(bcadd($a,$b),2);
$b = bcsqrt(bcmul($b,$y));
$d = bcsub($y,$a);
$t = bcsub($t,bcmul(bcmul($d,$d),$x));
$x = bcmul(2,$x);
$c--;
} while ($c > 0);
$c = bcadd($a,$b);
return bcdiv(bcmul($c,$c),bcmul(4,$t));
}
//Sine
//x-x^3/3!+x^5/5!-x^7/7!+...
function sin_($a,$b) {
$c = bcmul(bcmul($a,$a),$a);
$d = 6;
$e = $a;
$f = 3;
do {
if ((++$f / 2) & 1) $e = bcadd($e,bcdiv($c,$d));
else $e = bcsub($e,bcdiv($c,$d));
$d = bcmul(bcmul($d,$f),++$f);
$c = bcmul(bcmul($c,$a),$a);
$b--;
} while ($b > 0);
return $e;
}
//Cosine
//1-x^2/2!+x^4/4!-x^6/6!+...
function cos_($a,$b) {
$c = bcmul($a,$a);
$d = 2;
$e = 1;
$f = 2;
do {
if ((++$f / 2) & 1) $e = bcsub($e,bcdiv($c,$d));
else $e = bcadd($e,bcdiv($c,$d));
$d = bcmul(bcmul($d,$f),++$f);
$c = bcmul(bcmul($c,$a),$a);
$b--;
} while ($b > 0);
return $e;
}
//Tangent
function tan_($a,$b) {
return bcdiv(sin_($a,$b),cos_($a,$b));
}
//Greatest Common Divisor
function gcd($a,$b) {
do {
if (!($a = bcmod($a,$b))) return $b;
if (!($b = bcmod($b,$a))) return $a;
} while (1);
}
//Find n´th fibonacci number
function fibonacci($a) {
/*$b = bcsqrt(5);
$c = bcdiv(bcadd($b,1),2);
return bcdiv(bcsub(bcpow($c,$a),bcpow(bcdiv(-1,$c),$a)),$b);*/
if ($a == 0) return 0;
$b = 1;
$c = 0;
$e = 1;
while ($a > $e) {
$d = $b;
$b = bcadd($b,$c,0);
$c = $d;
$e++;
}
return $b;
}
----
Manual Page -- http://www.php.net/manual/en/ref.bc.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44985
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44985&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44985&report=yes
Search -- http://master.php.net/manage/user-notes.php