PHP写的求多项式导数的函数代码

yipeiwu_com5年前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

相关文章

PHP基于闭包思想实现的BT(torrent)文件解析工具实例详解

本文实例讲述了PHP基于闭包思想实现的torrent文件解析工具。分享给大家供大家参考,具体如下: PHP对静态词法域的支持有点奇怪,内部匿名函数必须在参数列表后面加上use关键字,显式...

PHP正则表达式替换站点关键字链接后空白的解决方法

标题这样不知道合适不合适。具体的情况是这样的:网站要增加关键字链接功能,然后需要对文章的内容进行正则表达式匹配并替换,然后使用了preg_replace函数。替换的程序代码如下:...

PHP删除数组中的特定元素的代码

比如下面的程序: 复制代码 代码如下: <?php $arr = array('apple','banana','cat','dog'); unset($arr[2]); prin...

php遍历替换目录下文件指定内容的方法

本文实例讲述了php遍历替换目录下文件指定内容的方法。分享给大家供大家参考,具体如下: 在php中目录访问需要遍历了然后文件需要一个个打开进行访问操作了,下面我们来看一段php 替换目录...

php实现网站顶踩功能的完整前端代码

许多网站都支持顶、踩功能,以便于显示用户对当前网页内容的满意度反馈。下面我们给出本站使用的顶、踩功能的完整前台实现代码,以便于用户参考。 完整的前端代码包括html、css、js各部分的...