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.
 
 
 
 
 
 

81 line
2.2 KiB

  1. /*
  2. * libcaca ASCII-Art library
  3. * Copyright (c) 2002, 2003 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 GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  19. * 02111-1307 USA
  20. */
  21. /** \file math.c
  22. * \version \$Id$
  23. * \author Sam Hocevar <sam@zoy.org>
  24. * \brief Math
  25. *
  26. * This file contains simple mathematical routines.
  27. */
  28. #include "config.h"
  29. #include <stdlib.h>
  30. #include "caca.h"
  31. #include "caca_internals.h"
  32. /**
  33. * \brief Generate a random integer within a range.
  34. *
  35. * \param min The lower bound of the integer range.
  36. * \param max The upper bound of the integer range.
  37. * \return A random integer comprised between \p min and \p max, inclusive.
  38. */
  39. int caca_rand(int min, int max)
  40. {
  41. return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
  42. }
  43. /**
  44. * \brief Approximate a square root, using Newton's method to avoid
  45. * costly floating point calculations.
  46. *
  47. * \param a A positive integer.
  48. * \return The approximate square root of \p a.
  49. */
  50. unsigned int caca_sqrt(unsigned int a)
  51. {
  52. if(a == 0)
  53. return 0;
  54. if(a < 1000000000)
  55. {
  56. unsigned int x = a < 10 ? 1
  57. : a < 1000 ? 10
  58. : a < 100000 ? 100
  59. : a < 10000000 ? 1000
  60. : 10000;
  61. /* Newton's method. Three iterations would be more than enough. */
  62. x = (x * x + a) / x / 2;
  63. x = (x * x + a) / x / 2;
  64. x = (x * x + a) / x / 2;
  65. x = (x * x + a) / x / 2;
  66. return x;
  67. }
  68. return 2 * caca_sqrt(a / 4);
  69. }