25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

math.c 1.7 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. }