How do I compute the second derivative of an one dimensional array in C#? has anyone done this before ?
CodePudding user response:
You can declare an extension method that returns pairs of sequential numbers:
public static IEnumerable<(T Previous, T Next)> PreviousAndNext<T>(this IEnumerable<T> self)
{
using (var iter = self.GetEnumerator())
{
if (!iter.MoveNext())
yield break;
var previous = iter.Current;
while (iter.MoveNext())
{
var next = iter.Current;
yield return (previous, next);
previous = next;
}
}
}
If you want the discrete derivative, i.e. difference between sequential numbers you would do: myArray.PreviousAndNext().Select((p, n) => n-p)
. If you want the second discrete derivative you would just repeat the function, i.e.
myArray.PreviousAndNext().Select((p, n) => n-p)
.PreviousAndNext().Select((p, n) => n-p);
You could repeat this pattern however many times you want.