Search code examples
c#arraysalgorithmnewtons-methodlinear-interpolation

Update values of array when a specific element is changed


Let us assume that I have defined a function named computeValue (double x):

  1. whose input is a double value
  2. that returns a value obtained by performing a certain set of operations using the elements of an array, to be described below.

Also, we have the above mentioned array that

  1. is some class's member
  2. contains only 4 positions.
  3. The 1st position contains a certain value, the 4th contains another value that will be the input to our function
  4. (here comes the tricky bit), the 2nd and 3rd values of the array should be the result of a linear interpolation between positions 1 and 4 of the array. That is, if we modify the position 1 or 4 of the array, then positions 2 and 3 should change their values automatically according to the interpolation method.

My aim is to invoke a root-finding algorithm (such as Newton-Raphson, Secant Method, etc) that will aim to minimize the following expression:

f = CONSTANT - computeValue(array[4])

As you may have already observed, the problem is that every time my root-finding routine modifies the 4th element of my array to obtain a new solution, the positions 2 and 3 of my array should be modified accordingly given that they are the result of a interpolation (as mentioned in point 4 above), thus changing the result of computeValue.

What is a possible way of making the values of the array change dynamically as the root finding algorithm works its way towards the root? Maybe something to do with an array storing lambda expressions defining the interpolation?


Solution

  • It cannot be done with a classic array, but you can implement your own type that solves the problem. This type internally uses an array of length four and offers access by

    public int this[int index]    
    {
        // get and set accessors
    }
    

    Here, you can write your own getters and setters, so that you can recalculate values as soon as the others were changed.