Quartiles.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 Quartiles(IList<float> list)
  10. {
  11. if (list.Count < 4) throw new ArgumentException("list must not be empty");
  12. var sorted = list.OrderBy(v => v).ToList();
  13. var i1 = 0.25f * list.Count;
  14. var i2 = 0.5f * list.Count;
  15. var i3 = 0.75f * list.Count;
  16. Q1 = ValueForFloatingIndex(sorted, i1);
  17. Q2 = ValueForFloatingIndex(sorted, i2);
  18. Q3 = ValueForFloatingIndex(sorted, i3);
  19. Iqr = Q3 - Q1;
  20. }
  21. public float Q1 { get; }
  22. public float Q2 { get; }
  23. public float Q3 { get; }
  24. public float Iqr { get; }
  25. private float ValueForFloatingIndex(IList<float> list, float index)
  26. {
  27. var i = Mathf.Max(0, index - 1);
  28. if (i % 1f == 0) return list[(int) i];
  29. var flooredIndex = Mathf.FloorToInt(i);
  30. var lower = list[flooredIndex];
  31. var higher = list[Mathf.Min(Mathf.CeilToInt(i), list.Count - 1)];
  32. return Mathf.Lerp(lower, higher, i - flooredIndex);
  33. }
  34. }
  35. }