source: libcaca/trunk/src/math.c @ 205

Last change on this file since 205 was 205, checked in by Sam Hocevar, 19 years ago
  • src/: + Doxygenated a few things.
  • Property svn:keywords set to Id
File size: 1.8 KB
Line 
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
22/**  \file math.c
23 *   \version \$Id: math.c 205 2003-11-22 12:45:25Z sam $
24 *   \author Sam Hocevar <sam@zoy.org>
25 *   \brief Math functions
26 *
27 *   This file contains simple mathematical routines.
28 */
29
30#include "config.h"
31
32#include <stdlib.h>
33
34#include "caca.h"
35#include "caca_internals.h"
36
37int caca_rand(int min, int max)
38{
39    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
40}
41
42unsigned int caca_sqrt(unsigned int a)
43{
44    if(a == 0)
45        return 0;
46
47    if(a < 1000000000)
48    {
49        unsigned int x = a < 10 ? 1
50                       : a < 1000 ? 10
51                       : a < 100000 ? 100
52                       : a < 10000000 ? 1000
53                       : 10000;
54
55        /* Newton's method. Three iterations would be more than enough. */
56        x = (x * x + a) / x / 2;
57        x = (x * x + a) / x / 2;
58        x = (x * x + a) / x / 2;
59        x = (x * x + a) / x / 2;
60
61        return x;
62    }
63
64    return 2 * caca_sqrt(a / 4);
65}
66
Note: See TracBrowser for help on using the repository browser.