多项式方程的确定度

问题描述 投票:0回答:1

我正在编写最适合求解器的多项式行作为有趣的学期中断项目。

给出输入:一个多项式(即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个数度。

当前的小岛存放在一个

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]

有什么方法可以根据多项式的阶数来公式化方程式。我不想为每个系数硬编码度数。根据给定的inout。

谢谢

c polynomial-math best-fit-curve
1个回答
0
投票

不确定是否要问这个,但是如果您想知道数组的大小,可以执行以下操作:

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

[“以后再使用该方程式不确定您的意思”。如果您只是想评估函数,我认为最有效的方法是使用霍纳算法:

#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/

如果有帮助,我也将其放在一个副本中:https://repl.it/repls/CumbersomeLeanEquipment

© www.soinside.com 2019 - 2024. All rights reserved.