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

Last change on this file since 257 was 257, checked in by Sam Hocevar, 19 years ago
  • src/: + Doxygenated public functions.
  • Property svn:keywords set to Id
File size: 2.2 KB
RevLine 
[89]1/*
[185]2 *   libcaca       ASCII-Art library
[89]3 *   Copyright (c) 2002, 2003 Sam Hocevar <sam@zoy.org>
4 *                 All Rights Reserved
5 *
[192]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.
[89]10 *
[192]11 *   This library is distributed in the hope that it will be useful,
[89]12 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
[192]13 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 *   Lesser General Public License for more details.
[89]15 *
[192]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
[89]20 */
21
[205]22/**  \file math.c
23 *   \version \$Id: math.c 257 2003-12-18 00:11:52Z sam $
24 *   \author Sam Hocevar <sam@zoy.org>
25 *   \brief Math functions
26 *
27 *   This file contains simple mathematical routines.
28 */
29
[89]30#include "config.h"
31
32#include <stdlib.h>
33
[185]34#include "caca.h"
35#include "caca_internals.h"
[89]36
[257]37/**
38 * \brief Generate a random integer within a range.
39 *
40 * \param min The lower bound of the integer range.
41 * \param max The upper bound of the integer range.
42 * \return A random integer comprised between \p min and \p max, inclusive.
43 */
[185]44int caca_rand(int min, int max)
[89]45{
[91]46    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
[89]47}
48
[257]49/**
50 * \brief Approximate a square root, using Newton's method to avoid
51 *        costly floating point calculations.
52 *
53 * \param a A positive integer.
54 * \return The approximate square root of \p a.
55 */
[185]56unsigned int caca_sqrt(unsigned int a)
[89]57{
[171]58    if(a == 0)
59        return 0;
[89]60
[171]61    if(a < 1000000000)
[89]62    {
[171]63        unsigned int x = a < 10 ? 1
64                       : a < 1000 ? 10
65                       : a < 100000 ? 100
66                       : a < 10000000 ? 1000
67                       : 10000;
[89]68
[171]69        /* Newton's method. Three iterations would be more than enough. */
70        x = (x * x + a) / x / 2;
71        x = (x * x + a) / x / 2;
72        x = (x * x + a) / x / 2;
73        x = (x * x + a) / x / 2;
[89]74
[171]75        return x;
76    }
[89]77
[185]78    return 2 * caca_sqrt(a / 4);
[89]79}
80
Note: See TracBrowser for help on using the repository browser.