Changeset 172 for ttyvaders


Ignore:
Timestamp:
Nov 14, 2003, 5:55:58 PM (16 years ago)
Author:
Sam Hocevar
Message:
  • libee/math.c: + ee_sqrt() now uses unsigned ints. + Avoid overflows in ee_sqrt().
Location:
ttyvaders/trunk/libee
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • ttyvaders/trunk/libee/ee.h

    r160 r172  
    9696
    9797int ee_rand(int, int);
    98 int ee_sqrt(int);
     98unsigned int ee_sqrt(unsigned int);
    9999
    100100struct ee_sprite * ee_load_sprite(const char *);
  • ttyvaders/trunk/libee/math.c

    r160 r172  
    3333}
    3434
    35 int ee_sqrt(int a)
     35unsigned int ee_sqrt(unsigned int a)
    3636{
    37     int x;
     37    if(a == 0)
     38        return 0;
    3839
    39     if(a <= 0)
     40    if(a < 1000000000)
    4041    {
    41         return 0;
     42        unsigned int x = a < 10 ? 1
     43                       : a < 1000 ? 10
     44                       : a < 100000 ? 100
     45                       : a < 10000000 ? 1000
     46                       : 10000;
     47
     48        /* Newton's method. Three iterations would be more than enough. */
     49        x = (x * x + a) / x / 2;
     50        x = (x * x + a) / x / 2;
     51        x = (x * x + a) / x / 2;
     52        x = (x * x + a) / x / 2;
     53
     54        return x;
    4255    }
    4356
    44     x = a > 100000 ? 1000 : a > 1000 ? 100 : a > 10 ? 10 : 1;
    45 
    46     /* Newton's method. Three iterations would be more than enough. */
    47     x = (x * x + a) / x / 2;
    48     x = (x * x + a) / x / 2;
    49     x = (x * x + a) / x / 2;
    50     x = (x * x + a) / x / 2;
    51 
    52     return x;
     57    return 2 * ee_sqrt(a / 4);
    5358}
    5459
Note: See TracChangeset for help on using the changeset viewer.