Java 二分法:计算多项式函数
我正在实现二分法,作为第一步,我需要计算多项式函数,但我没有得到正确的结果 使用的多项式是Java 二分法:计算多项式函数,java,algorithm,bisection,Java,Algorithm,Bisection,我正在实现二分法,作为第一步,我需要计算多项式函数,但我没有得到正确的结果 使用的多项式是3(x^2)+7(x)+1 使用x=2,结果应为27 public static double evaluaFx(int []coef, int grade, int x) { //int x viene siendo los x0,xf.xmenter code here double Fx=0; //System.out.println("grade"+grade+"x"+x);
3(x^2)+7(x)+1
使用
x=2
,结果应为27
public static double evaluaFx(int []coef, int grade, int x) {
//int x viene siendo los x0,xf.xmenter code here
double Fx=0;
//System.out.println("grade"+grade+"x"+x);
//for (int i = grade; i >=0; i--) {
// System.out.println(coef[i]);
//}
for (int i = grade; i>=0; i--) {
Fx= Math.pow((coef[i]*x), grade);
// System.out.println(Fx+"mas"+"("+coef[i]+x+") a la grado"+grade);
}
return Fx;
}
上述算法有什么问题?您的算法有几个问题: 一个等级(步骤
i
)的公式应为:
// for instance, if i=2, you want 3 * x^2 which translate to
Fx = coef[i]*Math.pow(x, i);
然后,在for循环中,你不必累加连续的成绩计算,每一步都会失去先前的结果。您应该这样做(注意+=而不是=)
您能添加参数和预期输出吗?我使用了下一个多项式f(x)=3x^2+7x+1,其中f(x)=27重新表述和格式化
Fx += coef[i]*Math.pow(x, i);