gpt4 book ai didi

c++ - 在 C++ 中区分多项式的函数

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:22 27 4
gpt4 key购买 nike

我一直在努力解决这个问题,但没有成功。我想要做的就是区分多项式,如 P(x) = 3x^3 + 2x^2 + 4x + 5在代码的最后,程序应该评估这个函数并给我答案。

P(x) 的导数是 P'(x) = 3*3x^2 + 2*2x + 4*1。如果 x = 1,则答案为 17。无论我如何改变我的循环,我就是得不到那个答案。

    /*
x: value of x in the polynomial
c: array of coefficients
n: number of coefficients
*/
double derivePolynomial(double x, double c[], int n) {
double result = 0;
double p = 1;
int counter = 1;

for(int i=n-1; i>=0; i--) //backward loop
{
result = result + c[i]*p*counter;
counter++; // number of power
p = p*x;
}

return result;
}



//Output in main() looks like this

double x=1.5;
double coeffs[4]={3,2.2,-1,0.5};
int numCoeffs=4;

cout << " = " << derivePolynomial(x,coeffs,numCoeffs) << endl;

最佳答案

x ^ n 的导数是 n * x ^ (n - 1),但您正在计算完全不同的东西。

double der(double x, double c[], int n)
{
double d = 0;
for (int i = 0; i < n; i++)
d += pow(x, i) * c[i];
return d;
}

假设您的多项式的形式为 c0 + c1x + c2x ^ 2 + ...

,这会起作用

Demonstration, with another function that does the derivation as well.

编辑:避免使用 pow() 函数的替代解决方案,具有简单的求和和重复的乘法:

double der2(double x, double c[], int n)
{
double d = 0;
for (int i = 0; i < n - 1; i++) {
d *= x;
d += (n - i - 1) * c[i];
}
return d;
}

This works too.请注意,采用迭代方法的函数(不使用 pow() 的函数)期望它们的参数(系数)以相反的顺序排列。

关于c++ - 在 C++ 中区分多项式的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16702305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com