MathUtil.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using UnityEngine;
  3. namespace XCharts.Runtime
  4. {
  5. public static class MathUtil
  6. {
  7. public static double Abs(double d)
  8. {
  9. return d > 0 ? d : -d;
  10. }
  11. public static double Clamp(double d, double min, double max)
  12. {
  13. if (d >= min && d <= max) return d;
  14. else if (d < min) return min;
  15. else return max;
  16. }
  17. public static bool Approximately(double a, double b)
  18. {
  19. return Math.Abs(b - a) < Math.Max(0.000001f * Math.Max(Math.Abs(a), Math.Abs(b)), Mathf.Epsilon * 8);
  20. }
  21. public static double Clamp01(double value)
  22. {
  23. if (value < 0F)
  24. return 0F;
  25. else if (value > 1F)
  26. return 1F;
  27. else
  28. return value;
  29. }
  30. public static double Lerp(double a, double b, double t)
  31. {
  32. return a + (b - a) * Clamp01(t);
  33. }
  34. public static bool IsInteger(double value)
  35. {
  36. if (value == 0) return true;
  37. if (value >= -1 && value <= 1) return false;
  38. return Math.Abs(value % 1) <= (Double.Epsilon * 100);
  39. }
  40. public static int GetPrecision(double value)
  41. {
  42. if (IsInteger(value)) return 0;
  43. int count = 1;
  44. double intvalue = value * Mathf.Pow(10, count);
  45. while (!IsInteger(intvalue) && count < 38)
  46. {
  47. count++;
  48. intvalue = value * Mathf.Pow(10, count);
  49. }
  50. return count;
  51. }
  52. }
  53. }