gsl_histogram__find.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* histogram/find.c
  2. *
  3. * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. */
  19. /* determines whether to optimize for linear ranges */
  20. #define LINEAR_OPT 1
  21. static int find (const size_t n, const double range[],
  22. const double x, size_t * i);
  23. static int
  24. find (const size_t n, const double range[], const double x, size_t * i)
  25. {
  26. size_t i_linear, lower, upper, mid;
  27. if (x < range[0])
  28. {
  29. return -1;
  30. }
  31. if (x >= range[n])
  32. {
  33. return +1;
  34. }
  35. /* optimize for linear case */
  36. #ifdef LINEAR_OPT
  37. {
  38. double u = (x - range[0]) / (range[n] - range[0]);
  39. i_linear = (size_t) (u * n);
  40. }
  41. if (x >= range[i_linear] && x < range[i_linear + 1])
  42. {
  43. *i = i_linear;
  44. return 0;
  45. }
  46. #endif
  47. /* perform binary search */
  48. upper = n ;
  49. lower = 0 ;
  50. while (upper - lower > 1)
  51. {
  52. mid = (upper + lower) / 2 ;
  53. if (x >= range[mid])
  54. {
  55. lower = mid ;
  56. }
  57. else
  58. {
  59. upper = mid ;
  60. }
  61. }
  62. *i = lower ;
  63. /* sanity check the result */
  64. if (x < range[lower] || x >= range[lower + 1])
  65. {
  66. GSL_ERROR ("x not found in range", GSL_ESANITY);
  67. }
  68. return 0;
  69. }