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 IE中下载附件问题解决方法

重点: 1、在IE中下载附件之前要清空缓存。 2、中文文件名要用urlencode编码。 复制代码 代码如下: Header("Pragma: "); //不加的话,IE中会提示目标主机...

讲解WordPress开发中一些常用的debug技巧

讲解WordPress开发中一些常用的debug技巧

在开发过程中,调试代码是非常重要的工作,而掌握一些 WordPress 的调试技巧,可以更好的进行调试。比如,在本地开发环境,你可能需要把全部的代码警告信息全部输出出来,方便修改代码不合...

PHP使用zlib扩展实现GZIP压缩输出的方法详解

本文实例讲述了PHP使用zlib扩展实现GZIP压缩输出的方法。分享给大家供大家参考,具体如下: 一般情况下我们出现大量数据传输理希望减少服务器的带宽压力,会采取一种方式来压缩文件传输,...

php HTML无刷新提交表单

通常对于无刷新提交表单,我们都是运用ajax实现的。前段时间跟着老大了解到另一种无刷新提交表单的方法,是利用iframe框架实现的。现在整理出来分享给大家。 第一种: html页面...

PHP使用curl函数发送Post请求的注意事项

前言 前几天在工作中遇到了一个需求,当用户点击了某个按钮以后,后台发起一个post请求到我这里,我接受传递过来的数据。一开始同事是用公司框架公共封装的http_request()方法进行...