Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

94 рядки
2.1 KiB

  1. /*
  2. * libcucul Unicode canvas library
  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. #include <stdlib.h>
  20. #include "cucul.h"
  21. #include "cucul_internals.h"
  22. /**
  23. * \brief Generate a random integer within a range.
  24. *
  25. * \param min The lower bound of the integer range.
  26. * \param max The upper bound of the integer range.
  27. * \return A random integer comprised between \p min and \p max, inclusive.
  28. */
  29. int cucul_rand(int min, int max)
  30. {
  31. return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
  32. }
  33. /**
  34. * \brief Approximate a square root, using Newton's method to avoid
  35. * costly floating point calculations.
  36. *
  37. * \param a A positive integer.
  38. * \return The approximate square root of \p a.
  39. */
  40. unsigned int cucul_sqrt(unsigned int a)
  41. {
  42. if(a == 0)
  43. return 0;
  44. if(a < 1000000000)
  45. {
  46. unsigned int x = a < 10 ? 1
  47. : a < 1000 ? 10
  48. : a < 100000 ? 100
  49. : a < 10000000 ? 1000
  50. : 10000;
  51. /* Newton's method. Three iterations would be more than enough. */
  52. x = (x * x + a) / x / 2;
  53. x = (x * x + a) / x / 2;
  54. x = (x * x + a) / x / 2;
  55. x = (x * x + a) / x / 2;
  56. return x;
  57. }
  58. return 2 * cucul_sqrt(a / 4);
  59. }
  60. /**
  61. * \brief powf substitute (x^y)
  62. * \param x The value to be raised
  63. * \param y The power to raise x of.
  64. * \return \p x raised to the power of \p y
  65. */
  66. float cucul_powf(float x, float y)
  67. {
  68. int i=((int)y);
  69. float r=x;
  70. if(((int)y)==1 || ((int)x)==1)
  71. return x;
  72. i--;
  73. while(i--)
  74. {
  75. r*=x;
  76. }
  77. return r;
  78. }