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

關於PHP求多項式導數的函數碼

不言
發布: 2023-04-01 16:08:01
原創
3104 人瀏覽過

PHP寫的求多項式導數的函數碼,需要的朋友可以參考下方

<?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 will 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.00000

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP網!

相關推薦:

在php中產生隨機數的3種方法

如何使用php動態產生版權所有訊息的方法

#

以上是關於PHP求多項式導數的函數碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板