我有这个代码来计算牛顿的除法差分插值,但它是给我错误的值,这是什么错误的代码?
package divided.differnece;
import java.text.*;
import java.math.*;
import java.util.*;
public class DividedDiffernece {
static float term(int i, float v, float x[]) {
float ter = 1;
for (int j = 0; j < i; j++) {
ter = ter * (v - x[j]);
}
return ter;
}
static void divided_differences_table (float x[], float y[][], int n){
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
y[j][i] = (y[j][i - 1] - y[j + 1]
[i - 1]) / (x[j] - x[i + j]);
}
}
}
static float Formula(float v, float x[], float y[][], int n) {
float sum = y[0][0];
for (int i = 1; i < n; i++) {
sum = sum + (term(i, v, x) * y[0][i]);
}
return sum;
}
static void print_divided_differences_table(float[] x, float[][] y, int n) {
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("****************************************************Divided Difference Interpolation Table*******************************************************************");
for (int i = 0; i < n; i++)
{
System.out.print(x[i]+"\t ");
for (int j = 0; j < n - i; j++)
{
String str1 = df.format(y[i][j]);
System.out.print(str1+"\t ");
}
System.out.println("\n");
}
}
public static void main(String[] args) {
System.out.print("_______________________________ X Values ________________________________\n\n");
Scanner Input = new Scanner(System.in);
int n = 5;
float P = 0 ;
float y[][] = new float [10][10];
float x[] = new float [n];
for (int i = 0; i < n; i++)
{
int l= i+1;
System.out.print("Enter x["+l+"]: ");
x[i] = Input.nextFloat();
}
System.out.print("\n_______________________________ Y Values ________________________________\n\n");
for (int i = 0; i < n; i++)
{
int l= i+1;
System.out.print("Enter y["+l+"][0]: ");
y[i][0] = Input.nextFloat();
}
System.out.print("\n_______________________________ The approxmiate F(x) ________________________________\n\n");
System.out.print("Enter X for finding F(x): ");
P = Input.nextFloat();
divided_differences_table ( x, y, n);
print_divided_differences_table(x, y, n);
// print the value
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("\nValue at "+df.format(P)+" is "
+df.format(Formula(P, x, y, n)));
}
}
正确的输出应该是这样的:
但密码告诉我:
暂无答案!
目前还没有任何答案,快来回答吧!