Number of Samples in the Exceedence Series

I have a series of data in IEnumrable<double> .

Let the dummy data:

 0 0 0 1 1.6 2.5 3.5 2.51 1.0 0 0 0 2.52 3.5 6.5 4.5 1.2 1.0 2.53 3.5 

let my Exceedence value be 1.5, so I want to calculate the amount of time that my value goes beyond 1.5 (basically, the number of 1.5 horizontal rows is reduced). In the above case, it will be 3 ({1.6-2.51}, {2.52-4.5}, {2.53-3.5}).

I can do this by iterating through each element and saving the count every time it rises or falls in value of Exceedence.

I am wondering if there is a way to do this using a LINQ query.

+6
source share
4 answers

Is this what you want?

  bool isAbove = false; int count = yourList.Count(x => { if (x > 1.5 && !isAbove) { isAbove = true; return true; } else if (x < 1.5) { isAbove = false; } return false; }); 
+5
source

You can use this helper function that will give you all ranges above your limit

 public IEnumerable<IEnumerable<double>> GetRangesAboveLimit(IEnumerable<double> source, double limit) { //keep going until we've processed the entire range while (source.Any()) { //skip elements below the limit source = source.SkipWhile(e => e <= limit); //yield the elements above the limit yield return source.TakeWhile(e => e > limit); //now skip those elements and then continue source = source.SkipWhile(e => e > limit); } } 

Then you can use it as follows:

 var range = new double [] { /* initialise here */ }; var rangesAboveLimit = GetRangesAboveLimit(range, 1.5); 

This will allow you not only to calculate the number of ranges above your limit (3), but also allow you to see the values โ€‹โ€‹of these ranges.

The results for your specific example are as follows:

enter image description here

+1
source

Just for fun - the same result using the Jon Skeet extension method "SelectPairs" ( link ):

 yourList.SelectPairs((x,y) => (x < 1.5 && y > 1.5) ? 1 : 0).Sum() 

But this does not work if there is only one value in the list.

PS DoctaJonez answer FTW! :)

0
source

This is probably not the best way to do this, but it is not an easy way to do this using LINQ.

 float[] numbers = { 0f, 0f, 0f, 1f, 1.6f, 2.5f, 3.5f, 2.51f, 1.0f, 0f, 0f, 0f, 2.52f, 3.5f, 6.5f, 4.5f, 1.2f, 1.0f, 2.53f, 3.5f }; int count = numbers.Where((n, i) => i > 0 && n > 1.5f && numbers[i - 1] < 1.5f).Count(); 
0
source

Source: https://habr.com/ru/post/885402/


All Articles