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

Last change on this file since 540 was 540, checked in by Sam Hocevar, 14 years ago
  • Polished the driver split a bit (still no events, except resize events), properly credited authors and documented a few things.
  • Property svn:keywords set to Id
File size: 2.1 KB
RevLine 
[89]1/*
[527]2 *  libcucul      Unicode canvas library
3 *  Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
[268]4 *                All Rights Reserved
[89]5 *
[268]6 *  This library is free software; you can redistribute it and/or
[522]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.
[89]10 */
11
[268]12/** \file math.c
13 *  \version \$Id: math.c 540 2006-03-07 09:17:35Z sam $
14 *  \author Sam Hocevar <sam@zoy.org>
[298]15 *  \brief Math
[205]16 *
[268]17 *  This file contains simple mathematical routines.
[205]18 */
19
[89]20#include "config.h"
21
22#include <stdlib.h>
23
[524]24#include "cucul.h"
25#include "cucul_internals.h"
[89]26
[257]27/**
28 * \brief Generate a random integer within a range.
29 *
30 * \param min The lower bound of the integer range.
31 * \param max The upper bound of the integer range.
32 * \return A random integer comprised between \p min and \p max, inclusive.
33 */
[524]34int cucul_rand(int min, int max)
[89]35{
[91]36    return min + (int)((1.0*(max-min+1)) * rand() / (RAND_MAX+1.0));
[89]37}
38
[257]39/**
40 * \brief Approximate a square root, using Newton's method to avoid
41 *        costly floating point calculations.
42 *
43 * \param a A positive integer.
44 * \return The approximate square root of \p a.
45 */
[524]46unsigned int cucul_sqrt(unsigned int a)
[89]47{
[171]48    if(a == 0)
49        return 0;
[89]50
[171]51    if(a < 1000000000)
[89]52    {
[171]53        unsigned int x = a < 10 ? 1
54                       : a < 1000 ? 10
55                       : a < 100000 ? 100
56                       : a < 10000000 ? 1000
57                       : 10000;
[89]58
[171]59        /* Newton's method. Three iterations would be more than enough. */
60        x = (x * x + a) / x / 2;
61        x = (x * x + a) / x / 2;
62        x = (x * x + a) / x / 2;
63        x = (x * x + a) / x / 2;
[89]64
[171]65        return x;
66    }
[89]67
[524]68    return 2 * cucul_sqrt(a / 4);
[89]69}
70
[495]71
72/**
73 * \brief powf substitute (x^y)
74 * \param x The value to be raised
75 * \param y The power to raise x of.
76 * \return \p x raised to the power of \p y
77 */
78
[524]79float cucul_powf(float x, float y)
[495]80{
81    int i=((int)y);
82    float r=x;
83
84    if(((int)y)==1 || ((int)x)==1)
85        return x;
86
87    i--;
88    while(i--)
89    {
90        r*=x;
91    }
92    return r;
93}
Note: See TracBrowser for help on using the repository browser.