如何在方法中编辑数组?

问题描述

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

2x^2 + 3x^1 + 2.0

不知道从这里开始做什么来改变数组的系数。

解决方法

您可以返回一个新的 int 数组 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--;
    }
}
,

您可以通过应用 Horner's method 获得结果。这也显示了结果系数。

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

使用Horner's Method求解让result = 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