How do I compute the second derivative of an one dimensional array in C#? has anyone done this before ?
Asked
Active
Viewed 90 times
-3
-
Try to be more specific. Do you mean you have a single array of values, for example y = [1, 7, 17, 31, 49, 71, 97], and you want to assume a constant dx value, and therefore compute the approximate (i.e. mean) derivative and 2nd derivative? – Joshua Huber May 18 '22 at 22:19
-
1First differences approximate the first derivative; second differences the second. https://en.wikipedia.org/wiki/Finite_difference – duffymo May 18 '22 at 23:23
-
at Joshua Huber Yes that is what I mean – TerriB4545 May 19 '22 at 03:34
-
lol see I was specific , because you knew what I was talking about – TerriB4545 May 19 '22 at 03:35
-
[like so?](https://stackoverflow.com/questions/28902728/c-sharp-method-for-element-by-element-difference-of-an-array-derivative-approxi) – TaW May 19 '22 at 05:26
1 Answers
0
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.

JonasH
- 28,608
- 2
- 10
- 23