使用PHP怎么书写一个求多项式导数的函数

发布时间:2021-01-26 09:03:40 作者:Leah
来源:亿速云 阅读:155

使用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.000000

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Python求离散序列导数的示例
  2. PyTorch 导数应用的使用教程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:利用php怎么获取当月的最后一天

下一篇:手机内核版本指的是什么意思

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》