Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * libcucul Canvas for ultrafast compositing of Unicode letters
  3. * Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
  4. * All Rights Reserved
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the Do What The Fuck You Want To
  8. * Public License, Version 2, as published by Sam Hocevar. See
  9. * http://sam.zoy.org/wtfpl/COPYING for more details.
  10. */
  11. /** \file math.c
  12. * \version \$Id$
  13. * \author Sam Hocevar <sam@zoy.org>
  14. * \brief Math
  15. *
  16. * This file contains simple mathematical routines.
  17. */
  18. #include "config.h"
  19. #if !defined(__KERNEL__)
  20. # include <stdlib.h>
  21. #endif
  22. #include "cucul.h"
  23. #include "cucul_internals.h"
  24. /**
  25. * \brief Generate a random integer within a range.
  26. *
  27. * \param min The lower bound of the integer range.
  28. * \param max The upper bound of the integer range.
  29. * \return A random integer comprised between \p min and \p max, inclusive.
  30. */
  31. int cucul_rand(int min, int max)
  32. {
  33. return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
  34. }
  35. /**
  36. * \brief Approximate a square root, using Newton's method to avoid
  37. * costly floating point calculations.
  38. *
  39. * \param a A positive integer.
  40. * \return The approximate square root of \p a.
  41. */
  42. unsigned int cucul_sqrt(unsigned int a)
  43. {
  44. if(a == 0)
  45. return 0;
  46. if(a < 1000000000)
  47. {
  48. unsigned int x = a < 10 ? 1
  49. : a < 1000 ? 10
  50. : a < 100000 ? 100
  51. : a < 10000000 ? 1000
  52. : 10000;
  53. /* Newton's method. Three iterations would be more than enough. */
  54. x = (x * x + a) / x / 2;
  55. x = (x * x + a) / x / 2;
  56. x = (x * x + a) / x / 2;
  57. x = (x * x + a) / x / 2;
  58. return x;
  59. }
  60. return 2 * cucul_sqrt(a / 4);
  61. }