首頁 >後端開發 >php教程 >PHP寫的求多項式導數的函數程式碼

PHP寫的求多項式導數的函數程式碼

黄舟
黄舟原創
2016-12-17 09:25:431279瀏覽

程式碼如下:


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 

derivative=26.000000 當x=12.000000內容,更多相關文章請關注PHP中文網(www.php.cn)!
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn