You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mathplus.h 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * =====================================================================================
  3. *
  4. * Filename: mathplus.h
  5. *
  6. * Description: Some extra math functions I use
  7. *
  8. * Version: 1.0
  9. * Created: 04/06/2014 05:52:24 PM
  10. * Revision: none
  11. * Compiler: gcc
  12. *
  13. * Author: YOUR NAME (),
  14. * Organization:
  15. *
  16. * =====================================================================================
  17. */
  18. #include <cmath>
  19. namespace mp {
  20. inline constexpr int floor_div3(int a, int b) {
  21. int d = a / b;
  22. return d * b == a ? d : d - ((a < 0) ^ (b < 0));
  23. }
  24. //Convert value to one within min/max. Useful for angles n' shit
  25. template <typename T>
  26. T normalize(const T& value, const T& min, const T& max) {
  27. return fmod((value - min), (max - min)) + min;
  28. }
  29. //Proportional normalization
  30. template <typename T>
  31. T scale(const T& value, const T& min, const T& max) {
  32. return (value - min) / (max - min);
  33. }
  34. //get sign of number
  35. template <typename T> int signum(const T& val) {
  36. return (T(0) < val) - (val < T(0));
  37. }
  38. //floating point modulus
  39. template <typename T> T mod(const T& a, const T& b) {
  40. return fmod(fmod(a,b) + b, b);
  41. }
  42. // constrain a value to bounds
  43. template <typename T>
  44. T constrain(const T& value, const T& min, const T& max) {
  45. if (value <= min) return min;
  46. if (value >= max) return max;
  47. return value;
  48. }
  49. template <typename T> T bound(const T& s, const T& ds) {
  50. if (ds < 0) {
  51. return bound(-s, -ds);
  52. }
  53. double ns = mod(s, (T)1);
  54. return (1-ns)/ds;
  55. }
  56. }