c - 确定多项式方程的次数
问题描述
我正在编写一个多项式最佳拟合求解器,作为一个有趣的学期休息项目。
给定输入:多项式的次数(即 2)和他们想要使用的一组点
167, 563
264, 429
410, 562
使用最小二乘逼近法,在求解矩阵时,您会得到系统的以下系数:
x^0 = 1270.1336927645
x^1 = -5.9573736115
x^2 = 0.0103176055
方程为
y= (0.01031760552017095)x^2 + (-5.95737361147607913)x^1 + (1270.13369276445428113)x^0
现在,我想在以后使用这个等式。
但是,我可以用 n 个度数写出这些方程吗?
目前,coefs 存储在一个
double A[];
所以如果我有一个 4 度的多项式,我知道等式将是
y = A[4]x^4 + A[3]x^3 + A[2]x^2 + A[1]x^1 + A[0]x^0
** 或者 **
y = A[4]*x*x*x*x + A[3]*x*x*x + A[2]*x*x + A[1]*x + A[0]
如果我有一个 5 度的多项式,我的方程将是
y = A[5]x^5 + A[4]x^4 + A[3]x^3 + A[2]x^2 + A[1]x^1 + A[0]x^0
或者
y = A[5]*x*x*x*x*x + A[4]*x*x*x*x + A[3]*x*x*x + A[2]*x*x + A[1]*x + A[0]
有什么方法可以根据多项式的次数来制定方程。我不想硬编码每个 coef 的学位。基于给定的输入输出。
谢谢
解决方案
我不确定这是否是您要问的,但是如果您想知道数组的大小,可以执行以下操作:
size_t n = sizeof(A)/sizeof(A[0]);//size of list divided by size of first element (should be 8 for double)
degree = (int)n - 1; //degree of the poly is one minus this
不确定“以后再使用该方程”是什么意思如果您只是想能够评估该函数,我认为最有效的方法是使用 horner 算法:
#include <stdio.h>
double horner(double *poly, double x,int degree)
{
double result = poly[0]; // Initialize result (poly[0] should be coeff of x^(degree))
// Evaluate value of polynomial using Horner's method
for (int i=1; i<=degree; i++){
result = result*x + poly[i];
}
return result;
}
int main(void) {
double poly[] = {1.0,2.0,-1.0,5.0};
//x^3+2x^2-1x+5 @ 3.0 should get 47.0
// use the n we found earlier
int n = sizeof(poly)/sizeof(poly[0]) - 1;
double x = 3.0;
printf("%f",horner(poly, x,n));
//should print 47
return 0;
}
改编自:https ://www.geeksforgeeks.org/horners-method-polynomial-evaluation/
如果有帮助,我也将其放入 repl 中:https ://repl.it/repls/CumbersomeLeanEquipment
推荐阅读
- azure-iot-hub - ScrapeFrequencyInSecs 在度量收集器模块中不起作用
- angular - 如何在Angular中使用相同的值初始化地图
- javascript - 如何在洗牌之前保存数组的旧状态
- r - 如何删除每列中的两个重复项之一并将它们合并到 r
- visual-studio-code - HTML 的 VS Code 自定义自动完成 - CSS 类名、数据属性
- java - 在 Netbeans 平台应用程序的 jPanel 中添加 JCEF 浏览器
- php - Laravel 新建的播种机不存在
- swift - 如何通过情节提要在启动屏幕视图上配置具有相对值的 UIImageView?
- javascript - 反应路由的路由顺序,有关系吗?
- google-cloud-build - 由于测试名称重复,CloudBuild 作业失败