如何使用 Java 中的牛顿多项式从给定的 x 和 f(x) 点生成插值函数?
这是我的代码:
Double[] x = {1.0, 2.0, 3.0};
Double[] fx = {1.0, 8.0, 27.0};
s = x.length;
Double[][] newton = new Double[(2*s)-1][s+1];
for(int i=0, z=0;i<s;i++,z+=2){
newton[z][0]=x[i];
newton[z][1]=fx[i];
}
int i=1, ii=2, j=2, ss=s;
for(int z=0;z<s-1;z++,j++,ss-=1,ii++){
for(int y=0;y<ss-1;y++,i+=2){
newton[i][j]=(newton[i+1][j-1]-newton[i-1][j-1])/(newton[i+(ii-1)][0]-newton[i-(ii-1)][0]);
}
i=ii;
}
}
对于丑陋的代码感到抱歉。给定 x 点 = {1, 2, 3} 和 f(x) = {1, 8, 27},上面的代码将生成一个如下所示的二维数组:
1.0 1.0
7.0
2.0 8.0 6.0
19.0
3.0 27.0
这是一个划分的差异表。
然后,我想生成它的插值多项式函数。因此,在上面的示例中,使用牛顿多项式规则,输出函数应为 1 + 7(x-1) + 6(x-1)(x-2) = 6x^2-11x+6。我真的很困惑,任何人都可以帮助我如何产生这样的输出吗?
Here's my code:
Double[] x = {1.0, 2.0, 3.0};
Double[] fx = {1.0, 8.0, 27.0};
s = x.length;
Double[][] newton = new Double[(2*s)-1][s+1];
for(int i=0, z=0;i<s;i++,z+=2){
newton[z][0]=x[i];
newton[z][1]=fx[i];
}
int i=1, ii=2, j=2, ss=s;
for(int z=0;z<s-1;z++,j++,ss-=1,ii++){
for(int y=0;y<ss-1;y++,i+=2){
newton[i][j]=(newton[i+1][j-1]-newton[i-1][j-1])/(newton[i+(ii-1)][0]-newton[i-(ii-1)][0]);
}
i=ii;
}
}
Sorry for the ugly code. Given x points = {1, 2, 3} and f(x) = {1, 8, 27}, the above code would produce a 2-dimension array like this:
1.0 1.0
7.0
2.0 8.0 6.0
19.0
3.0 27.0
which is a divided difference table.
Then, I want to generate its interpolating polynomial function. Thus, with above example, using Newton's polynomial rule, the output function should be 1 + 7(x-1) + 6(x-1)(x-2) = 6x^2-11x+6. I'm really stuck on this, can anyone help me how to produce an output like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我从牛顿插值中可以理解的,根据你的差异和你想要的x位置牛顿多项式的系数,对吗?
这里有一个小东西可以解决这个问题:
它用双精度数组表示多项式:
{1.0, 3.0, -2.0}
表示1 + 3x -2x^2
。这简化了计算(特别是多项式乘积)。执行结果为:
这是您期望的多项式
6 - 11x + 6x^2
。From what I could understand from newtonian interpolation, from your divided differences and your x-positions you want the coefficients of the Newton polynom, right ?
Here is a little thing that should do the trick:
It represents polynoms by arrays of doubles:
{1.0, 3.0, -2.0}
represents1 + 3x -2x^2
. This eases computations (notably polynoms product).The execution gives:
which is the polynom
6 - 11x + 6x^2
that you expected.