The code is as follows:
<?php
function Getderivativebyformulaandxdata ($formula, $x _data) {
$xArray = Explode ("+", $formula);
$Derivative = 0;
foreach ($xArray as $x _record) {
$tmpArray = Explode ("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 = 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];
}
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=%f\n", $max _derivative);
foreach ($matchs as $x _match) {
printf ("Derivative=%f when x=%f\n", $derivatives [$x _match], $x _match);
}
}
Notice the format of formula:ax^b if b=0 could omit except coefficient A, if a=1 could omit coefficient
$formula = "X^2+2x^1+1";
Print "The formula is $formula \ n";
printf ("Derivative of 2 is%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 "Sample x values: $STR \ n";
Getmaxderivativebyformulaandxdatas ($formula, $sampleData, $matchs). " \ n ";
?>
The output would be:
Sample x values:-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
Max derivative=26.000000
derivative=26.000000 when x=12.000000
These are the contents of the function code written by PHP to find the derivative of the polynomial, more relevant articles please pay attention to topic.alibabacloud.com (www.php.cn)!