程式碼如下:
function getDerivativeByFormulaAndXDATA($formula, $x_data){
$xArray =explode("+", $formula);
$導數 = 0;
foreach ($xArray as $x_record) {
$tmpArray =explode("x^", $x_record);
if(count($tmpArray) == 2){
$coefficient = $tmpArray[0]==""?1:$tmpArray[0];
$exp = $tmpArray[1];
}
// 常數
else {
$coefficient = $tmpArray[0];
$exp = 0;
}
$導數 += $因數*$exp*pow($x_data,$exp-1);
}
回傳 $導數;
}
function getValueByFormulaAndXDATA($formula, $x_data){
$xArray =explode("+", $formula);
$y_data = 0;
foreach ($xArray as $x_record) {
$tmpArray =explode("x^", $x_record);
if(count($tmpArray) == 2){
$coefficient = $tmpArray[0]==""?1:$tmpArray[0];
$exp = $tmpArray[1];
}
// 常數
else {
$coefficient = $tmpArray[0];
$exp = 0;
}
$y_data += $coefficient*pow($x_data,$exp);
}
回傳$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, 導數=%f n",$x_data, $derivative);
}
$matchs = array();
foreach ($derivatives as $x_data=>$derivative) {
if(abs($derivative) == $max_derivative){
$matchs[] = $x_data;
}
}
printf("最大導數=%fn",$max_derivative);
foreach ($matchs as $x_match) {
printf("當x=%fn 時導數=%f",$derivatives[$x_match], $x_match);
}
}
//注意公式的格式:ax^b 若b=0可以省除係數a以外的部分,如果a=1可以省掉係數
$formula = "x^2+2x^1+1 " ;
print "公式是 $formula n";
//printf("2 的導數是 %f n",getDerivativeByFormulaAndXDATA($formula, 3.2));
//列印 getValueByFormulaAndXDATA($formula, 3.2)."n";
$sampleData = 吞吐量(-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.", ";
}
列印「樣本x值:$str n」;
getMaxDerivativeByFormulaAndXDATAS($formula, $sampleData, $matchs)."n";
? , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
max導數=26.000000