PHP write the polynomial derivative of the function code, the need for friends can refer to the next
<?php function Getderivativebyformulaandxdata ($formula, $x _data) {$xArray = explode ("+", $formula); $Derivative = 0; F Oreach ($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 A S $x _record) {$tmpArray = explode ("x^", $x _record), if (count ($tmpArray) = = 2) {$coefficient = $tmpArray [0]== ""? 1: $tmpArra Y[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;}} prin TF ("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
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!