【发布时间】:2018-08-15 02:38:10
【问题描述】:
我正在使用 horners 方法创建可以计算多项式的代码,以及它对我给定的任何系数集的导数。当我对值进行硬编码时,霍纳的方法运行良好,但是当我更改代码以从命令行提示符获取任何输入时,霍纳的导数开始打印出带有数十个零的疯狂数字。但是多项式的霍纳方法仍在正确计算中。我不知道这段代码的错误在哪里。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
double horner(double *coeffs, int s, double x)
{
int i;
double res = 0.0;
for(i=s-1; i >= 0; i--)
{
res = res * x + coeffs[i];
}
return res;
}
double hornerDerivative(double *coeffs, int s_1, double x_1)
{
int i_1;
double res_1 = 0.0;
for(i_1 = s_1; i_1 >= 1; i_1--)
{
res_1 = res_1 * x_1 + i_1*coeffs[i_1];
}
return res_1;
}
double newton(double *coeffs, double a, double b, double eps)
{
int N = 0;
double c = ((a+b)/2);
while(N < 10)
{
double y = horner(coeffs, sizeof(coeffs), c);
double y_derivative = hornerDerivative(coeffs, sizeof(coeffs), c);
double c_1 = c - (y/y_derivative);
printf("c: %f\t",c);
printf("y: %f\t",y);
printf("y_der: %f\t",y_derivative);
printf("c_1: %f\n",c_1);
if(fabs(c_1-c)<eps)
{
return c_1;
}
c = c_1;
N = N + 1;
}
}
int main(int argc, char **argv)
{
printf("# of arguments%d\n\n\n\n", argc);
double coeffs[argc-3];
double a = atof(argv[argc-2]);
double b = atof(argv[argc-1]);
double eps = .001;
int i;
for(i=1; i < argc-2; i++)
{
coeffs[i-1] = atof(argv[argc-2-i]);
}
printf("The root of the equation is: %f\n", newton(coeffs, a, b, eps));
system("pause");
return 0;
}
这是我得到的输出。
C:\Dev-Cpp>ProgrammingAssignment1.exe 1 -6 4 12 1 4
# of arguments7
c: 2.500000 y: 0.125000 y_der: 61390858609268995000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 c_1: 2.500000
The root of the equation is: 2.500000
如您所见,horner 的方法可以很好地计算多项式,但不能正确计算导数。无论我对教授给我的列表中的系数使用什么示例,这始终是相同的错误。
【问题讨论】:
-
您不应将图像用作代码。使用文本。
-
欢迎来到 Stack Overflow。请直接在问题中包含您的代码——不要使用代码的图像,因为它不可读、不可复制、不可测试,因此无法调试。
-
就像@roottraveller 建议的那样,您永远不应该发布代码图像。除此之外,不要只是复制粘贴您尝试运行的整个代码。创建一个 minimal reproducible example 来恰当地演示问题。
-
您应该在阅读
coeffs 后尝试打印它们以确定确切的问题所在。 -
horner(coeffs, sizeof(coeffs), c);不会像您认为的那样做。coeffs是一个指针,所以sizeof(coeffs)是一个指针的大小。不是数组中的元素个数。
标签: c numerical-methods dev-c++