Skip to content
Advertisement

How to edit the array within a method?

So this method is called differentiate, and its purpose is to return a Poly object which consists of an array of doubles, this array should contain the coefficients of the differentiated polynomial for example if provided a poly object that contains an array with [2.0, 3.0, 2.0], the method will return [4, 3, 0] because 2x^2 + 3x^1 + 2.0‘s coefficients are those.

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--;
    }
}

Not sure what to do from here in order to change the array’s coefficients.

Advertisement

Answer

You can get the result by apply Horner’s method. This also shows the resulting coefficients.

  • original equation = y = 2x^3 + 6x^2 +4x + 3
  • after derivation = y' = 6x^2 + 12x + 4
  • given x = 3, the result is 54 + 36 + 4 = 94

To solve using Horner's Method let 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);

Prints

[6.0, 12.0, 4.0]
result = 94.0
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement