| 
<?
# Second version of deriv
 # Tread with caution
 
 class deriv {
 var $ds = array(
 'log(ax+b)' => 'd(ax+b)/(ax+b)',
 'cos(ax+b)' => '-1*sin(ax+b)*d(ax+b)',
 'sin(ax+b)' => '1*cos(ax+b)*d(ax+b)');
 function derivate_poly($function) {
 // Hybrid.
 // Function format: k(poly)^n + k(poly)^n etc...
 // k and n integers
 $q = explode(" ",$function);
 foreach ($q as $r => $s) {
 if (strlen($s) > 1) {
 $t = eregi("([0-9]+)\((.+)\)\^([0-9-])",$s,$w);
 if (is_array($w)) {
 if ($w[3] == 1) {
 $c1 = $w[1];
 $c2 = $this->derivate_single(str_replace("+"," + ",str_replace("-"," - ",$w[2])));
 $df[] = $c1*$c2."x^0";
 }
 elseif ($w[3] == 0) $df[] = 0;
 else {
 $c1 = $w[1]*$w[3];
 $pfin = $w[3]-1;
 $c2 = $this->derivate_single(str_replace("+"," + ",str_replace("-"," - ",$w[2])));
 if (is_int($c2)) {
 $c3 = $c1*$c2;
 $df[] = $c3."(".$w[2].")^".$pfin;
 }
 else {
 $df[] = $c1."(".$c2.")(".$w[2].")^".$pfin;
 }
 }
 }
 else $df[] = $s;
 }
 else $df[] = $t;
 }
 return implode($df);
 }
 function derivate_single($function) {
 // Fastest function for a straight polynomic
 // Format: kx^n + kx^n + kx^n
 // k and n integers. If no x, n=0
 $a = explode(" ",$function);
 foreach ($a as $b => $c) {
 if (strlen($c) > 1) {
 $r = eregi("([0-9]+)x\^([0-9-]+)",$c,$d);
 if (is_array($d)) {
 if ($d[2] > 1 or $d[2] < -1) $deriv[] = ($d[1]*$d[2])."x^".($d[2]-1);
 elseif (abs($d[2]) == 1) $deriv[] = $d[1];
 else array_pop($deriv);
 unset($d);
 }
 else $deriv[] = $c;
 }
 else $deriv[] = $c;
 }
 return implode(" ",$deriv);
 }
 }
 |