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

Last change on this file since 192 was 192, checked in by Sam Hocevar, 19 years ago
  • Changed copyleft to LGPL.
  • Property svn:keywords set to Id
File size: 1.6 KB
Line 
1/*
2 *   libcaca       ASCII-Art library
3 *   Copyright (c) 2002, 2003 Sam Hocevar <sam@zoy.org>
4 *                 All Rights Reserved
5 *
6 *   $Id: math.c 192 2003-11-16 12:28:29Z sam $
7 *
8 *   This library is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU Lesser General Public
10 *   License as published by the Free Software Foundation; either
11 *   version 2 of the License, or (at your option) any later version.
12 *
13 *   This library is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 *   Lesser General Public License for more details.
17 *
18 *   You should have received a copy of the GNU Lesser General Public
19 *   License along with this library; if not, write to the Free Software
20 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 *   02111-1307  USA
22 */
23
24#include "config.h"
25
26#include <stdlib.h>
27
28#include "caca.h"
29#include "caca_internals.h"
30
31int caca_rand(int min, int max)
32{
33    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
34}
35
36unsigned int caca_sqrt(unsigned int a)
37{
38    if(a == 0)
39        return 0;
40
41    if(a < 1000000000)
42    {
43        unsigned int x = a < 10 ? 1
44                       : a < 1000 ? 10
45                       : a < 100000 ? 100
46                       : a < 10000000 ? 1000
47                       : 10000;
48
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
55        return x;
56    }
57
58    return 2 * caca_sqrt(a / 4);
59}
60
Note: See TracBrowser for help on using the repository browser.