代码如下:
function getDerivativeByFormulaAndXDATA($formula, $x_data){
$xArray = explosion("+", $formula);
$Derivative = 0;
foreach ($xArray as $x_record) {
$tmpArray = explosion("x^", $x_record);
if(count($tmpArray) == 2){
$coefficient = $tmpArray[0]==""?1:$tmpArray[0];
$exp = $tmpArray[1];
}
//constant
else {
$coefficient = $tmpArray[0];
$exp = 0;
}
$Derivative += $coefficient*$exp*pow($x_data,$exp-1);
}
return $Derivative;
}
function getValueByFormulaAndXDATA($formula, $x_data){
$xArray = explosion("+", $formula);
$y_data = 0;
foreach ($xArray as $x_record) {
$tmpArray = explosion("x^", $x_record);
if(count($tmpArray) == 2){
$coefficient = $tmpArray[0]==""?1:$tmpArray[0];
$exp = $tmpArray[1];
}
//constant
else {
$coefficient = $tmpArray[0];
$exp = 0;
}
$y_data += $coefficient*pow($x_data,$exp);
}
return $y_data;
}
function getMaxDerivativeByFormulaAndXDATAS($formula, $x_datas, &$matchs){
$derivatives = array();
$max_derivative = 0;
foreach ($x_datas as $x_data) {
$derivative = getDerivativeByFormulaAndXDATA($formula, $x_data);
$derivatives[$x_data] = $derivative;
$max_derivative = $max_derivative>=abs($derivative)?$max_derivative:abs($derivative);
//printf("x=%f, derivative=%f n",$x_data, $derivative);
}
$matchs = array();
foreach ($derivatives as $x_data=>$derivative) {
if(abs($derivative) == $max_derivative){
$matchs[] = $x_data;
}
}
printf("max derivative=%fn",$max_derivative);
foreach ($matchs as $x_match) {
printf(" derivative=%f when x=%fn",$derivatives[$x_match], $x_match);
}
}
//Beachten Sie das Format der Formel: ax^b, wenn b=0 außer Koeffizient a weggelassen werden könnte, wenn a=1 den Koeffizienten weglassen könnte
$formula = "x^2+ 2x^1+1";
print „Die Formel ist $formel n“;
//printf("Ableitung von 2 ist %f n",getDerivativeByFormulaAndXDATA($formula, 3.2));
//print getValueByFormulaAndXDATA($formula, 3.2)."n";
$sampleData = array(-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3, 4,5,6,7,8,9,10,11,12);
foreach ($sampleData as $x_data) {
$str.=$x_data.", ";
}
print „Beispiel-X-Werte: $str n“;
getMaxDerivativeByFormulaAndXDATAS($formula, $sampleData, $matchs)."n";
?>
Die Ausgabe lautet:
Beispiel-X-Werte: -12, -11, -10, -9, -8, -7, -6, -5, -4 , -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
maximale Ableitung=26,000000
Ableitung=26,000000, wenn x= 12.000000
以上就是PHP写的求多项式导数的函数代码的内容,更多相关文章请关注PHP中文网(www.php.cn)!