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

Last change on this file since 536 was 536, checked in by Sam Hocevar, 14 years ago
  • Moved stuff around to differenciate between libcucul and libcaca.
  • Property svn:keywords set to Id
File size: 2.2 KB
Line 
1/*
2 *  libcucul      Unicode canvas library
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 536 2006-03-06 20:57:14Z 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(HAVE_INTTYPES_H) || defined(_DOXYGEN_SKIP_ME)
23#   include <inttypes.h>
24#else
25typedef unsigned char uint8_t;
26#endif
27
28#include <stdlib.h>
29
30#include "cucul.h"
31#include "cucul_internals.h"
32
33/**
34 * \brief Generate a random integer within a range.
35 *
36 * \param min The lower bound of the integer range.
37 * \param max The upper bound of the integer range.
38 * \return A random integer comprised between \p min and \p max, inclusive.
39 */
40int cucul_rand(int min, int max)
41{
42    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
43}
44
45/**
46 * \brief Approximate a square root, using Newton's method to avoid
47 *        costly floating point calculations.
48 *
49 * \param a A positive integer.
50 * \return The approximate square root of \p a.
51 */
52unsigned int cucul_sqrt(unsigned int a)
53{
54    if(a == 0)
55        return 0;
56
57    if(a < 1000000000)
58    {
59        unsigned int x = a < 10 ? 1
60                       : a < 1000 ? 10
61                       : a < 100000 ? 100
62                       : a < 10000000 ? 1000
63                       : 10000;
64
65        /* Newton's method. Three iterations would be more than enough. */
66        x = (x * x + a) / x / 2;
67        x = (x * x + a) / x / 2;
68        x = (x * x + a) / x / 2;
69        x = (x * x + a) / x / 2;
70
71        return x;
72    }
73
74    return 2 * cucul_sqrt(a / 4);
75}
76
77
78/**
79 * \brief powf substitute (x^y)
80 * \param x The value to be raised
81 * \param y The power to raise x of.
82 * \return \p x raised to the power of \p y
83 */
84
85float cucul_powf(float x, float y)
86{
87    int i=((int)y);
88    float r=x;
89
90    if(((int)y)==1 || ((int)x)==1)
91        return x;
92
93    i--;
94    while(i--)
95    {
96        r*=x;
97    }
98    return r;
99}
Note: See TracBrowser for help on using the repository browser.