如何在方法中编辑数组?



所以这个方法被称为微分,它的目的是返回一个由双精度数组组成的Poly对象,该数组应该包含微分多项式的系数,例如,如果提供一个包含[2.0, 3.0, 2.0]数组的Poly对象,该方法将返回[4, 3, 0],因为2x^2 + 3x^1 + 2.0的系数是那些。

public static Poly polyObject;
public static String differentiate(Poly polyObject) {
double[] array = polyObject.getDoubleArray();
int counterVariable = array.length - 1;
for (int i = 0; i < array.length; i++) {
array[i] = array[i] * counterVariable;
counterVariable--;
}
}

不知道该怎么做才能改变数组的系数。

可以应用Horner的方法得到结果。这也显示了结果系数。

  • 原方程=y = 2x^3 + 6x^2 +4x + 3
  • 推导后=y' = 6x^2 + 12x + 4
  • 给定x = 3,结果为54 + 36 + 4 = 94

Horner's Methodresult = 0

  • result = result * x + 6 = 6 ( exp = 2)
  • result = result * x + 12 = 30 (exp = 1)
  • result = result * x + 4 = 94 (exp = 0) - done!
double[] coefs = { 2., 6., 4., 3 };
int exp = coefs.length-1;
double result = 0;
int i = 0;
int x = 3; // the value to be solve
while(i < exp) {
coefs[i] *= (exp-i);
result = result * x + coefs[i++];
}

// y = 2x^3 + 6x^2 +4x + 3
// After derivation. coefs = 6, 12, 4
// y' = 6x^2 + 12x + 4    =    54 + 36 + 4
coefs = Arrays.copyOf(coefs,coefs.length-1);
System.out.println(Arrays.toString(coefs));
System.out.println("result = " + result);

打印

[6.0, 12.0, 4.0]
result = 94.0

您可以返回一个新的整数数组int[],如:

public static int[] differentiate(Poly polyObject) {
double[] array = polyObject.getDoubleArray();
int counterVariable = array.length - 1;
int[] coeffArray = new int[array.length];    
for(int i = 0; i < array.length; i++) {
coeffArray[i] = (int) array[i] * counterVariable;
counterVariable--;
}
return coeffArray;
}

或改变相同的数组,但你将有double类型的值,而不是int。这正是你的代码,但不是返回类型String改为void

public static void differentiate(Poly polyObject) {
double[] array = polyObject.getDoubleArray();
int counterVariable = array.length - 1;
for(int i=0; i < array.length; i++) {
array[i] = array[i] * counterVariable;
counterVariable--;
}
}

最新更新