2
0

Quartiles.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace AdditionalMathf
  6. {
  7. public class Quartiles
  8. {
  9. public float Q1 { get; }
  10. public float Q2 { get; }
  11. public float Q3 { get; }
  12. public float Iqr { get; }
  13. public Quartiles(IList<float> list)
  14. {
  15. if (list.Count < 4) throw new ArgumentException("list must not be empty");
  16. var sorted = list.OrderBy(v => v).ToList();
  17. var i1 = 0.25f * list.Count;
  18. var i2 = 0.5f * list.Count;
  19. var i3 = 0.75f * list.Count;
  20. Q1 = ValueForFloatingIndex(sorted, i1);
  21. Q2 = ValueForFloatingIndex(sorted, i2);
  22. Q3 = ValueForFloatingIndex(sorted, i3);
  23. Iqr = Q3 - Q1;
  24. }
  25. private float ValueForFloatingIndex(IList<float> list, float index)
  26. {
  27. var i = Mathf.Max(0, index - 1);
  28. if (i % 1f == 0)
  29. {
  30. return list[(int) i];
  31. }
  32. var flooredIndex = Mathf.FloorToInt(i);
  33. var lower = list[flooredIndex];
  34. var higher = list[Mathf.Min(Mathf.CeilToInt(i), list.Count - 1)];
  35. return Mathf.Lerp(lower, higher, i - flooredIndex);
  36. }
  37. }
  38. }