source: libcaca/trunk/cucul/math.c @ 773

Last change on this file since 773 was 773, checked in by Sam Hocevar, 14 years ago
  • Improved documentation in many places.
  • Property svn:keywords set to Id
File size: 1.7 KB
Line 
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: math.c 773 2006-04-14 12:10:18Z sam $
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/*
15 *  This file contains simple mathematical routines.
16 */
17
18#include "config.h"
19
20#if !defined(__KERNEL__)
21#   include <stdlib.h>
22#endif
23
24#include "cucul.h"
25#include "cucul_internals.h"
26
27/** \brief Generate a random integer within a range.
28 *
29 *  \param min The lower bound of the integer range.
30 *  \param max The upper bound of the integer range.
31 *  \return A random integer comprised between \p min and \p max, inclusive.
32 */
33int cucul_rand(int min, int max)
34{
35    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
36}
37
38/** \brief Approximate a square root, using Newton's method to avoid
39 *         costly floating point calculations.
40 *
41 *  \param a A positive integer.
42 *  \return The approximate square root of \p a.
43 */
44unsigned int cucul_sqrt(unsigned int a)
45{
46    if(a == 0)
47        return 0;
48
49    if(a < 1000000000)
50    {
51        unsigned int x = a < 10 ? 1
52                       : a < 1000 ? 10
53                       : a < 100000 ? 100
54                       : a < 10000000 ? 1000
55                       : 10000;
56
57        /* Newton's method. Three iterations would be more than enough. */
58        x = (x * x + a) / x / 2;
59        x = (x * x + a) / x / 2;
60        x = (x * x + a) / x / 2;
61        x = (x * x + a) / x / 2;
62
63        return x;
64    }
65
66    return 2 * cucul_sqrt(a / 4);
67}
68
Note: See TracBrowser for help on using the repository browser.