Ignore:
Timestamp:
Mar 10, 2006, 10:31:32 AM (14 years ago)
Author:
Sam Hocevar
Message:
  • Implemented a few math functions in our kernel: cos(), sin(), sqrt().
Location:
libcaca/trunk/kernel
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • libcaca/trunk/kernel/kernel.c

    r573 r578  
    212212}
    213213
     214/* math.h functions */
     215double cos(double x)
     216{
     217    double ret = 0.0;
     218    double x2;
     219    double num = 1.0;
     220    double fact = 1.0;
     221    int i;
     222
     223    x = x - ((double)(int)(x / (2 * M_PI))) * (2 * M_PI);
     224    x2 = x * x;
     225
     226    /* cos(x) = 1/0! - x^2/2! + x^4/4! - x^6/6! ... */
     227    for(i = 0; i < 10; i++)
     228    {
     229        ret += num / fact;
     230        num *= - x2;
     231        fact *= (2 * i + 1) * (2 * i + 2);
     232    }
     233
     234    return ret;
     235}
     236
     237double sin(double x)
     238{
     239    double ret = 0.0;
     240    double x2;
     241    double num;
     242    double fact = 1.0;
     243    int i;
     244
     245    x = x - ((double)(int)(x / (2 * M_PI))) * (2 * M_PI);
     246    x2 = x * x;
     247    num = x;
     248
     249    /* sin(x) = x/1! - x^3/3! + x^5/5! - x^7/7! ... */
     250    for(i = 0; i < 10; i++)
     251    {
     252        ret += num / fact;
     253        num *= - x2;
     254        fact *= (2 * i + 2) * (2 * i + 3);
     255    }
     256
     257    return ret;
     258}
     259
     260double sqrt(double x)
     261{
     262    double ret = x;
     263    int i;
     264
     265    /* This is Newton's method */
     266    for(i = 0; i < 10; i++)
     267        ret = (ret * ret + x) / (ret * 2.0);
     268
     269    return ret;
     270}
     271
    214272#endif /* __KERNEL__ */
  • libcaca/trunk/kernel/kernel.h

    r573 r578  
    2525#define RAND_MAX ((unsigned int)0x8000000)
    2626#define INT_MAX ((int)0x7fffffff)
     27#define M_PI 3.14159265358979323846
    2728#define __BYTE_ORDER 1
    2829#define __BIG_ENDIAN 2
     
    111112int gettimeofday(struct timeval *tv, struct timezone *tz);
    112113
     114/* math.h functions */
     115double cos(double x);
     116double sin(double x);
     117double sqrt(double x);
     118
Note: See TracChangeset for help on using the changeset viewer.