ningshuxia
2022-12-12 4f1314cb69a47c22e52f1efdc4b4be6c1d55143d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// <copyright file="StreamingStatistics.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2015 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
 
using System;
using System.Collections.Generic;
using System.Linq;
using Complex = System.Numerics.Complex;
 
namespace IStation.Numerics.Statistics
{
    /// <summary>
    /// Statistics operating on an IEnumerable in a single pass, without keeping the full data in memory.
    /// Can be used in a streaming way, e.g. on large datasets not fitting into memory.
    /// </summary>
    /// <seealso cref="SortedArrayStatistics"/>
    /// <seealso cref="StreamingStatistics"/>
    /// <seealso cref="Statistics"/>
    public static class StreamingStatistics
    {
        /// <summary>
        /// Returns the smallest value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double Minimum(IEnumerable<double> stream)
        {
            double min = double.PositiveInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (d < min || double.IsNaN(d))
                {
                    min = d;
                }
 
                any = true;
            }
 
            return any ? min : double.NaN;
        }
 
        /// <summary>
        /// Returns the smallest value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static float Minimum(IEnumerable<float> stream)
        {
            float min = float.PositiveInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (d < min || float.IsNaN(d))
                {
                    min = d;
                }
 
                any = true;
            }
 
            return any ? min : float.NaN;
        }
 
        /// <summary>
        /// Returns the largest value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double Maximum(IEnumerable<double> stream)
        {
            double max = double.NegativeInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (d > max || double.IsNaN(d))
                {
                    max = d;
                }
 
                any = true;
            }
 
            return any ? max : double.NaN;
        }
 
        /// <summary>
        /// Returns the largest value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static float Maximum(IEnumerable<float> stream)
        {
            float max = float.NegativeInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (d > max || float.IsNaN(d))
                {
                    max = d;
                }
 
                any = true;
            }
 
            return any ? max : float.NaN;
        }
 
        /// <summary>
        /// Returns the smallest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double MinimumAbsolute(IEnumerable<double> stream)
        {
            double min = double.PositiveInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (Math.Abs(d) < min || double.IsNaN(d))
                {
                    min = Math.Abs(d);
                }
 
                any = true;
            }
 
            return any ? min : double.NaN;
        }
 
        /// <summary>
        /// Returns the smallest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static float MinimumAbsolute(IEnumerable<float> stream)
        {
            float min = float.PositiveInfinity;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (Math.Abs(d) < min || float.IsNaN(d))
                {
                    min = Math.Abs(d);
                }
 
                any = true;
            }
 
            return any ? min : float.NaN;
        }
 
        /// <summary>
        /// Returns the largest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double MaximumAbsolute(IEnumerable<double> stream)
        {
            double max = 0.0d;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (Math.Abs(d) > max || double.IsNaN(d))
                {
                    max = Math.Abs(d);
                }
 
                any = true;
            }
 
            return any ? max : double.NaN;
        }
 
        /// <summary>
        /// Returns the largest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static float MaximumAbsolute(IEnumerable<float> stream)
        {
            float max = 0.0f;
            bool any = false;
 
            foreach (var d in stream)
            {
                if (Math.Abs(d) > max || float.IsNaN(d))
                {
                    max = Math.Abs(d);
                }
 
                any = true;
            }
 
            return any ? max : float.NaN;
        }
 
        /// <summary>
        /// Returns the smallest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static Complex MinimumMagnitudePhase(IEnumerable<Complex> stream)
        {
            double minMagnitude = double.PositiveInfinity;
            Complex min = new Complex(double.PositiveInfinity, double.PositiveInfinity);
            bool any = false;
 
            foreach (var d in stream)
            {
                double magnitude = d.Magnitude;
                if (double.IsNaN(magnitude))
                {
                    return new Complex(double.NaN, double.NaN);
                }
                if (magnitude < minMagnitude || magnitude == minMagnitude && d.Phase < min.Phase)
                {
                    minMagnitude = magnitude;
                    min = d;
                }
 
                any = true;
            }
 
            return any ? min : new Complex(double.NaN, double.NaN);
        }
 
        /// <summary>
        /// Returns the smallest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static Complex32 MinimumMagnitudePhase(IEnumerable<Complex32> stream)
        {
            float minMagnitude = float.PositiveInfinity;
            Complex32 min = new Complex32(float.PositiveInfinity, float.PositiveInfinity);
            bool any = false;
 
            foreach (var d in stream)
            {
                float magnitude = d.Magnitude;
                if (float.IsNaN(magnitude))
                {
                    return new Complex32(float.NaN, float.NaN);
                }
                if (magnitude < minMagnitude || magnitude == minMagnitude && d.Phase < min.Phase)
                {
                    minMagnitude = magnitude;
                    min = d;
                }
 
                any = true;
            }
 
            return any ? min : new Complex32(float.NaN, float.NaN);
        }
 
        /// <summary>
        /// Returns the largest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static Complex MaximumMagnitudePhase(IEnumerable<Complex> stream)
        {
            double maxMagnitude = 0.0d;
            Complex max = Complex.Zero;
            bool any = false;
 
            foreach (var d in stream)
            {
                double magnitude = d.Magnitude;
                if (double.IsNaN(magnitude))
                {
                    return new Complex(double.NaN, double.NaN);
                }
                if (magnitude > maxMagnitude || magnitude == maxMagnitude && d.Phase > max.Phase)
                {
                    maxMagnitude = magnitude;
                    max = d;
                }
 
                any = true;
            }
 
            return any ? max : new Complex(double.NaN, double.NaN);
        }
 
        /// <summary>
        /// Returns the largest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static Complex32 MaximumMagnitudePhase(IEnumerable<Complex32> stream)
        {
            float maxMagnitude = 0.0f;
            Complex32 max = Complex32.Zero;
            bool any = false;
 
            foreach (var d in stream)
            {
                float magnitude = d.Magnitude;
                if (float.IsNaN(magnitude))
                {
                    return new Complex32(float.NaN, float.NaN);
                }
                if (magnitude > maxMagnitude || magnitude == maxMagnitude && d.Phase > max.Phase)
                {
                    maxMagnitude = magnitude;
                    max = d;
                }
 
                any = true;
            }
 
            return any ? max : new Complex32(float.NaN, float.NaN);
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double Mean(IEnumerable<double> stream)
        {
            double mean = 0;
            ulong m = 0;
            bool any = false;
 
            foreach (var d in stream)
            {
                mean += (d - mean)/++m;
                any = true;
            }
 
            return any ? mean : double.NaN;
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double Mean(IEnumerable<float> stream)
        {
            return Mean(stream.Select(x => (double)x));
        }
 
        /// <summary>
        /// Evaluates the geometric mean of the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double GeometricMean(IEnumerable<double> stream)
        {
            ulong m = 0;
            double sum = 0;
 
            foreach (var d in stream)
            {
                sum += Math.Log(d);
                m++;
            }
 
            return m > 0 ? Math.Exp(sum / m) : double.NaN;
        }
 
        /// <summary>
        /// Evaluates the geometric mean of the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double GeometricMean(IEnumerable<float> stream)
        {
            return GeometricMean(stream.Select(x => (double)x));
        }
 
        /// <summary>
        /// Evaluates the harmonic mean of the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double HarmonicMean(IEnumerable<double> stream)
        {
            ulong m = 0;
            double sum = 0;
 
            foreach (var d in stream)
            {
                sum += 1.0 / d;
                m++;
            }
 
            return m > 0 ? m/sum : double.NaN;
        }
 
        /// <summary>
        /// Evaluates the harmonic mean of the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double HarmonicMean(IEnumerable<float> stream)
        {
            return HarmonicMean(stream.Select(x => (double)x));
        }
 
        /// <summary>
        /// Estimates the unbiased population variance from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static double Variance(IEnumerable<double> samples)
        {
            double variance = 0;
            double sum = 0;
            ulong count = 0;
 
            using (var iterator = samples.GetEnumerator())
            {
                if (iterator.MoveNext())
                {
                    count++;
                    sum = iterator.Current;
                }
 
                while (iterator.MoveNext())
                {
                    count++;
                    double xi = iterator.Current;
                    sum += xi;
                    double diff = (count*xi) - sum;
                    variance += (diff*diff)/(count*(count - 1));
                }
            }
 
            return count > 1 ? variance/(count - 1) : double.NaN;
        }
 
        /// <summary>
        /// Estimates the unbiased population variance from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static double Variance(IEnumerable<float> samples)
        {
            return Variance(samples.Select(x => (double)x));
        }
 
        /// <summary>
        /// Evaluates the population variance from the full population provided as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population">Sample stream, no sorting is assumed.</param>
        public static double PopulationVariance(IEnumerable<double> population)
        {
            double variance = 0;
            double sum = 0;
            ulong count = 0;
 
            using (var iterator = population.GetEnumerator())
            {
                if (iterator.MoveNext())
                {
                    count++;
                    sum = iterator.Current;
                }
 
                while (iterator.MoveNext())
                {
                    count++;
                    double xi = iterator.Current;
                    sum += xi;
                    double diff = (count*xi) - sum;
                    variance += (diff*diff)/(count*(count - 1));
                }
            }
 
            return variance/count;
        }
 
        /// <summary>
        /// Evaluates the population variance from the full population provided as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population">Sample stream, no sorting is assumed.</param>
        public static double PopulationVariance(IEnumerable<float> population)
        {
            return PopulationVariance(population.Select(x => (double)x));
        }
 
        /// <summary>
        /// Estimates the unbiased population standard deviation from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static double StandardDeviation(IEnumerable<double> samples)
        {
            return Math.Sqrt(Variance(samples));
        }
 
        /// <summary>
        /// Estimates the unbiased population standard deviation from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static double StandardDeviation(IEnumerable<float> samples)
        {
            return Math.Sqrt(Variance(samples));
        }
 
        /// <summary>
        /// Evaluates the population standard deviation from the full population provided as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population">Sample stream, no sorting is assumed.</param>
        public static double PopulationStandardDeviation(IEnumerable<double> population)
        {
            return Math.Sqrt(PopulationVariance(population));
        }
 
        /// <summary>
        /// Evaluates the population standard deviation from the full population provided as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population">Sample stream, no sorting is assumed.</param>
        public static double PopulationStandardDeviation(IEnumerable<float> population)
        {
            return Math.Sqrt(PopulationVariance(population));
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN for mean if data is empty or any entry is NaN, and NaN for variance if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static Tuple<double, double> MeanVariance(IEnumerable<double> samples)
        {
            double mean = 0;
            double variance = 0;
            double sum = 0;
            ulong count = 0;
 
            using (var iterator = samples.GetEnumerator())
            {
                if (iterator.MoveNext())
                {
                    count++;
                    sum = mean = iterator.Current;
                }
 
                while (iterator.MoveNext())
                {
                    count++;
                    double xi = iterator.Current;
                    sum += xi;
                    double diff = (count * xi) - sum;
                    variance += (diff * diff) / (count * (count - 1));
                    mean += (xi - mean) / count;
                }
            }
 
            return new Tuple<double, double>(
                count > 0 ? mean : double.NaN,
                count > 1 ? variance/(count - 1) : double.NaN);
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN for mean if data is empty or any entry is NaN, and NaN for variance if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static Tuple<double, double> MeanVariance(IEnumerable<float> samples)
        {
            return MeanVariance(samples.Select(x => (double)x));
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN for mean if data is empty or any entry is NaN, and NaN for standard deviation if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static Tuple<double, double> MeanStandardDeviation(IEnumerable<double> samples)
        {
            var meanVariance = MeanVariance(samples);
            return new Tuple<double, double>(meanVariance.Item1, Math.Sqrt(meanVariance.Item2));
        }
 
        /// <summary>
        /// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as enumerable sequence, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN for mean if data is empty or any entry is NaN, and NaN for standard deviation if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples">Sample stream, no sorting is assumed.</param>
        public static Tuple<double, double> MeanStandardDeviation(IEnumerable<float> samples)
        {
            return MeanStandardDeviation(samples.Select(x => (double)x));
        }
 
        /// <summary>
        /// Estimates the unbiased population covariance from the provided two sample enumerable sequences, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples1">First sample stream.</param>
        /// <param name="samples2">Second sample stream.</param>
        public static double Covariance(IEnumerable<double> samples1, IEnumerable<double> samples2)
        {
            // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
            var n = 0;
            var mean1 = 0.0;
            var mean2 = 0.0;
            var comoment = 0.0;
 
            using (var s1 = samples1.GetEnumerator())
            using (var s2 = samples2.GetEnumerator())
            {
                while (s1.MoveNext())
                {
                    if (!s2.MoveNext())
                    {
                        throw new ArgumentException("All vectors must have the same dimensionality.");
                    }
 
                    var mean2Prev = mean2;
                    n++;
                    mean1 += (s1.Current - mean1)/n;
                    mean2 += (s2.Current - mean2)/n;
                    comoment += (s1.Current - mean1)*(s2.Current - mean2Prev);
                }
 
                if (s2.MoveNext())
                {
                    throw new ArgumentException("All vectors must have the same dimensionality.");
                }
            }
 
            return n > 1 ? comoment/(n - 1) : double.NaN;
        }
 
        /// <summary>
        /// Estimates the unbiased population covariance from the provided two sample enumerable sequences, in a single pass without memoization.
        /// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
        /// Returns NaN if data has less than two entries or if any entry is NaN.
        /// </summary>
        /// <param name="samples1">First sample stream.</param>
        /// <param name="samples2">Second sample stream.</param>
        public static double Covariance(IEnumerable<float> samples1, IEnumerable<float> samples2)
        {
            return Covariance(samples1.Select(x => (double)x), samples2.Select(x => (double)x));
        }
 
        /// <summary>
        /// Evaluates the population covariance from the full population provided as two enumerable sequences, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population1">First population stream.</param>
        /// <param name="population2">Second population stream.</param>
        public static double PopulationCovariance(IEnumerable<double> population1, IEnumerable<double> population2)
        {
            // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
            var n = 0;
            var mean1 = 0.0;
            var mean2 = 0.0;
            var comoment = 0.0;
 
            using (var p1 = population1.GetEnumerator())
            using (var p2 = population2.GetEnumerator())
            {
                while (p1.MoveNext())
                {
                    if (!p2.MoveNext())
                    {
                        throw new ArgumentException("All vectors must have the same dimensionality.");
                    }
 
                    var mean2Prev = mean2;
                    n++;
                    mean1 += (p1.Current - mean1) / n;
                    mean2 += (p2.Current - mean2) / n;
                    comoment += (p1.Current - mean1) * (p2.Current - mean2Prev);
                }
 
                if (p2.MoveNext())
                {
                    throw new ArgumentException("All vectors must have the same dimensionality.");
                }
            }
 
            return comoment/n;
        }
 
        /// <summary>
        /// Evaluates the population covariance from the full population provided as two enumerable sequences, in a single pass without memoization.
        /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
        /// Returns NaN if data is empty or if any entry is NaN.
        /// </summary>
        /// <param name="population1">First population stream.</param>
        /// <param name="population2">Second population stream.</param>
        public static double PopulationCovariance(IEnumerable<float> population1, IEnumerable<float> population2)
        {
            return PopulationCovariance(population1.Select(x => (double)x), population2.Select(x => (double)x));
        }
 
        /// <summary>
        /// Estimates the root mean square (RMS) also known as quadratic mean from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double RootMeanSquare(IEnumerable<double> stream)
        {
            double mean = 0;
            ulong m = 0;
            bool any = false;
 
            foreach (var d in stream)
            {
                mean += (d*d - mean)/++m;
                any = true;
            }
 
            return any ? Math.Sqrt(mean) : double.NaN;
        }
 
        /// <summary>
        /// Estimates the root mean square (RMS) also known as quadratic mean from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static double RootMeanSquare(IEnumerable<float> stream)
        {
            return RootMeanSquare(stream.Select(x => (double)x));
        }
 
        /// <summary>
        /// Calculates the entropy of a stream of double values.
        /// Returns NaN if any of the values in the stream are NaN.
        /// </summary>
        /// <param name="stream">The input stream to evaluate.</param>
        /// <returns></returns>
        public static double Entropy(IEnumerable<double> stream)
        {
            // http://en.wikipedia.org/wiki/Shannon_entropy
 
            var index = new Dictionary<double, double>();
 
            // count the number of occurrences of each item in the stream
            int totalCount = 0;
            foreach (double value in stream)
            {
                if (double.IsNaN(value))
                {
                    return double.NaN;
                }
 
                double currentValueCount;
                if (index.TryGetValue(value, out currentValueCount))
                {
                    index[value] = ++currentValueCount;
                }
                else
                {
                    index.Add(value, 1);
                }
 
                ++totalCount;
            }
 
            // calculate the entropy of the stream
            double entropy = 0;
            foreach (var item in index)
            {
                double p = item.Value / totalCount;
                entropy += p * Math.Log(p, 2);
            }
 
            return -entropy;
        }
    }
}