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.
 
 
 
 
 
 

69 rivejä
1.7 KiB

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