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 | |
---|

12 | /** \file math.c |
---|

13 | * \version \$Id: math.c 683 2006-03-24 09:30:02Z sam $ |
---|

14 | * \author Sam Hocevar <sam@zoy.org> |
---|

15 | * \brief Math |
---|

16 | * |
---|

17 | * This file contains simple mathematical routines. |
---|

18 | */ |
---|

19 | |
---|

20 | #include "config.h" |
---|

21 | |
---|

22 | #if !defined(__KERNEL__) |
---|

23 | # include <stdlib.h> |
---|

24 | #endif |
---|

25 | |
---|

26 | #include "cucul.h" |
---|

27 | #include "cucul_internals.h" |
---|

28 | |
---|

29 | /** |
---|

30 | * \brief Generate a random integer within a range. |
---|

31 | * |
---|

32 | * \param min The lower bound of the integer range. |
---|

33 | * \param max The upper bound of the integer range. |
---|

34 | * \return A random integer comprised between \p min and \p max, inclusive. |
---|

35 | */ |
---|

36 | int cucul_rand(int min, int max) |
---|

37 | { |
---|

38 | return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0)); |
---|

39 | } |
---|

40 | |
---|

41 | /** |
---|

42 | * \brief Approximate a square root, using Newton's method to avoid |
---|

43 | * costly floating point calculations. |
---|

44 | * |
---|

45 | * \param a A positive integer. |
---|

46 | * \return The approximate square root of \p a. |
---|

47 | */ |
---|

48 | unsigned int cucul_sqrt(unsigned int a) |
---|

49 | { |
---|

50 | if(a == 0) |
---|

51 | return 0; |
---|

52 | |
---|

53 | if(a < 1000000000) |
---|

54 | { |
---|

55 | unsigned int x = a < 10 ? 1 |
---|

56 | : a < 1000 ? 10 |
---|

57 | : a < 100000 ? 100 |
---|

58 | : a < 10000000 ? 1000 |
---|

59 | : 10000; |
---|

60 | |
---|

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 | |
---|

67 | return x; |
---|

68 | } |
---|

69 | |
---|

70 | return 2 * cucul_sqrt(a / 4); |
---|

71 | } |
---|

72 | |
---|