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

相关文章

解析百度搜索结果link?url=参数分析 (全)

前几天写过一篇可以获取到百度跳转之后的网址的文章,在百度了一下,有人也研究过百度link?url=的。 大概得出如下结果: 1、加密方式根据:随机+输入停留时间+快照地址进行加密 2、整...

PHP中函数rand和mt_rand的区别比较

PHP函数rand和mt_rand    mt_rand() 比rand() 快四倍      很多老的 libc 的随机数发生器具有一些不确定和未知的特性而且很慢。PHP 的 rand...

php需登录的文件上传管理系统

本文给大家介绍一个不错的需要登录的php 文件上传管理系统,功能简单有需要了解的同学可参考。 代码如下 <?php $admin_pw="admin";//管理密码 $...

php实现MD5加密16位(不要默认的32位)

使用substr函数截取: 复制代码 代码如下:substr(md5("admin"),8,16); // 16位MD5加密 md5("admin"); // 32位MD5加密 ...

php阿拉伯数字转中文人民币大写

本文实例为大家分享了php阿拉伯数字转中文人民币大写的实现代码,供大家参考,具体代码如下 代码1:php阿拉伯数字转中文人民币大写,有详细的注释 /** *数字金额转换成中文大写金额...