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.
 
 
 
 
 
 

75 lines
1.8 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. * 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. static float powf_internal(float x, float y);
  25. /**
  26. * \brief Generate a random integer within a range.
  27. *
  28. * \param min The lower bound of the integer range.
  29. * \param max The upper bound of the integer range.
  30. * \return A random integer comprised between \p min and \p max, inclusive.
  31. */
  32. int cucul_rand(int min, int max)
  33. {
  34. return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
  35. }
  36. /**
  37. * \brief Approximate a square root, using Newton's method to avoid
  38. * costly floating point calculations.
  39. *
  40. * \param a A positive integer.
  41. * \return The approximate square root of \p a.
  42. */
  43. unsigned int cucul_sqrt(unsigned int a)
  44. {
  45. if(a == 0)
  46. return 0;
  47. if(a < 1000000000)
  48. {
  49. unsigned int x = a < 10 ? 1
  50. : a < 1000 ? 10
  51. : a < 100000 ? 100
  52. : a < 10000000 ? 1000
  53. : 10000;
  54. /* Newton's method. Three iterations would be more than enough. */
  55. x = (x * x + a) / x / 2;
  56. x = (x * x + a) / x / 2;
  57. x = (x * x + a) / x / 2;
  58. x = (x * x + a) / x / 2;
  59. return x;
  60. }
  61. return 2 * cucul_sqrt(a / 4);
  62. }