source: trunk/src/real.cpp @ 1013

Last change on this file since 1013 was 1013, checked in by sam, 11 years ago

core: remove most dependencies on real number size in the various math
functions.

File size: 24.5 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstring>
16#include <cstdio>
17
18#include "core.h"
19
20using namespace std;
21
22namespace lol
23{
24
25real::real(float f) { *this = (double)f; }
26real::real(int i) { *this = (double)i; }
27real::real(unsigned int i) { *this = (double)i; }
28
29real::real(double d)
30{
31    union { double d; uint64_t x; } u = { d };
32
33    uint32_t sign = (u.x >> 63) << 31;
34    uint32_t exponent = (u.x << 1) >> 53;
35
36    switch (exponent)
37    {
38    case 0x00:
39        m_signexp = sign;
40        break;
41    case 0x7ff:
42        m_signexp = sign | 0x7fffffffu;
43        break;
44    default:
45        m_signexp = sign | (exponent + (1 << 30) - (1 << 10));
46        break;
47    }
48
49    m_mantissa[0] = u.x >> 36;
50    m_mantissa[1] = u.x >> 20;
51    m_mantissa[2] = u.x >> 4;
52    m_mantissa[3] = u.x << 12;
53    memset(m_mantissa + 4, 0, sizeof(m_mantissa) - 4 * sizeof(m_mantissa[0]));
54}
55
56real::operator float() const { return (float)(double)(*this); }
57real::operator int() const { return (int)(double)(*this); }
58real::operator unsigned int() const { return (unsigned int)(double)(*this); }
59
60real::operator double() const
61{
62    union { double d; uint64_t x; } u;
63
64    /* Get sign */
65    u.x = m_signexp >> 31;
66    u.x <<= 11;
67
68    /* Compute new exponent */
69    uint32_t exponent = (m_signexp << 1) >> 1;
70    int e = (int)exponent - (1 << 30) + (1 << 10);
71
72    if (e < 0)
73        u.x <<= 52;
74    else if (e >= 0x7ff)
75    {
76        u.x |= 0x7ff;
77        u.x <<= 52;
78    }
79    else
80    {
81        u.x |= e;
82
83        /* Store mantissa if necessary */
84        u.x <<= 16;
85        u.x |= m_mantissa[0];
86        u.x <<= 16;
87        u.x |= m_mantissa[1];
88        u.x <<= 16;
89        u.x |= m_mantissa[2];
90        u.x <<= 4;
91        u.x |= m_mantissa[3] >> 12;
92        /* Rounding */
93        u.x += (m_mantissa[3] >> 11) & 1;
94    }
95
96    return u.d;
97}
98
99real real::operator +() const
100{
101    return *this;
102}
103
104real real::operator -() const
105{
106    real ret = *this;
107    ret.m_signexp ^= 0x80000000u;
108    return ret;
109}
110
111real real::operator +(real const &x) const
112{
113    if (x.m_signexp << 1 == 0)
114        return *this;
115
116    /* Ensure both arguments are positive. Otherwise, switch signs,
117     * or replace + with -. */
118    if (m_signexp >> 31)
119        return -(-*this + -x);
120
121    if (x.m_signexp >> 31)
122        return *this - (-x);
123
124    /* Ensure *this has the larger exponent (no need for the mantissa to
125     * be larger, as in subtraction). Otherwise, switch. */
126    if ((m_signexp << 1) < (x.m_signexp << 1))
127        return x + *this;
128
129    real ret;
130
131    int e1 = m_signexp - (1 << 30) + 1;
132    int e2 = x.m_signexp - (1 << 30) + 1;
133
134    int bigoff = (e1 - e2) / (sizeof(uint16_t) * 8);
135    int off = e1 - e2 - bigoff * (sizeof(uint16_t) * 8);
136
137    if (bigoff > BIGITS)
138        return *this;
139
140    ret.m_signexp = m_signexp;
141
142    uint32_t carry = 0;
143    for (int i = BIGITS; i--; )
144    {
145        carry += m_mantissa[i];
146        if (i - bigoff >= 0)
147            carry += x.m_mantissa[i - bigoff] >> off;
148
149        if (i - bigoff > 0)
150            carry += (x.m_mantissa[i - bigoff - 1] << (16 - off)) & 0xffffu;
151        else if (i - bigoff == 0)
152            carry += 0x0001u << (16 - off);
153
154        ret.m_mantissa[i] = carry;
155        carry >>= 16;
156    }
157
158    /* Renormalise in case we overflowed the mantissa */
159    if (carry)
160    {
161        carry--;
162        for (int i = 0; i < BIGITS; i++)
163        {
164            uint16_t tmp = ret.m_mantissa[i];
165            ret.m_mantissa[i] = (carry << 15) | (tmp >> 1);
166            carry = tmp & 0x0001u;
167        }
168        ret.m_signexp++;
169    }
170
171    return ret;
172}
173
174real real::operator -(real const &x) const
175{
176    if (x.m_signexp << 1 == 0)
177        return *this;
178
179    /* Ensure both arguments are positive. Otherwise, switch signs,
180     * or replace - with +. */
181    if (m_signexp >> 31)
182        return -(-*this + x);
183
184    if (x.m_signexp >> 31)
185        return (*this) + (-x);
186
187    /* Ensure *this is larger than x */
188    if (*this < x)
189        return -(x - *this);
190
191    real ret;
192
193    int e1 = m_signexp - (1 << 30) + 1;
194    int e2 = x.m_signexp - (1 << 30) + 1;
195
196    int bigoff = (e1 - e2) / (sizeof(uint16_t) * 8);
197    int off = e1 - e2 - bigoff * (sizeof(uint16_t) * 8);
198
199    if (bigoff > BIGITS)
200        return *this;
201
202    ret.m_signexp = m_signexp;
203
204    int32_t carry = 0;
205    for (int i = 0; i < bigoff; i++)
206    {
207        carry -= x.m_mantissa[BIGITS - i];
208        carry = (carry & 0xffff0000u) | (carry >> 16);
209    }
210    carry -= x.m_mantissa[BIGITS - 1 - bigoff] & ((1 << off) - 1);
211    carry /= (1 << off);
212
213    for (int i = BIGITS; i--; )
214    {
215        carry += m_mantissa[i];
216        if (i - bigoff >= 0)
217            carry -= x.m_mantissa[i - bigoff] >> off;
218
219        if (i - bigoff > 0)
220            carry -= (x.m_mantissa[i - bigoff - 1] << (16 - off)) & 0xffffu;
221        else if (i - bigoff == 0)
222            carry -= 0x0001u << (16 - off);
223
224        ret.m_mantissa[i] = carry;
225        carry = (carry & 0xffff0000u) | (carry >> 16);
226    }
227
228    carry += 1;
229
230    /* Renormalise if we underflowed the mantissa */
231    if (carry == 0)
232    {
233        /* How much do we need to shift the mantissa? FIXME: this could
234         * be computed above */
235        off = 0;
236        for (int i = 0; i < BIGITS; i++)
237        {
238            if (!ret.m_mantissa[i])
239            {
240                off += sizeof(uint16_t) * 8;
241                continue;
242            }
243
244            for (uint16_t tmp = ret.m_mantissa[i]; tmp < 0x8000u; tmp <<= 1)
245                off++;
246            break;
247        }
248        if (off == BIGITS * sizeof(uint16_t) * 8)
249            ret.m_signexp &= 0x80000000u;
250        else
251        {
252            off++; /* Shift one more to get rid of the leading one */
253            ret.m_signexp -= off;
254
255            bigoff = off / (sizeof(uint16_t) * 8);
256            off -= bigoff * sizeof(uint16_t) * 8;
257
258            for (int i = 0; i < BIGITS; i++)
259            {
260                uint16_t tmp = 0;
261                if (i + bigoff < BIGITS)
262                    tmp |= ret.m_mantissa[i + bigoff] << off;
263                if (i + bigoff + 1 < BIGITS)
264                    tmp |= ret.m_mantissa[i + bigoff + 1] >> (16 - off);
265                ret.m_mantissa[i] = tmp;
266            }
267        }
268    }
269
270    return ret;
271}
272
273real real::operator *(real const &x) const
274{
275    real ret;
276
277    if (m_signexp << 1 == 0 || x.m_signexp << 1 == 0)
278    {
279        ret = (m_signexp << 1 == 0) ? *this : x;
280        ret.m_signexp ^= x.m_signexp & 0x80000000u;
281        return ret;
282    }
283
284    ret.m_signexp = (m_signexp ^ x.m_signexp) & 0x80000000u;
285    int e = (m_signexp & 0x7fffffffu) - (1 << 30) + 1
286          + (x.m_signexp & 0x7fffffffu) - (1 << 30) + 1;
287
288    /* Accumulate low order product; no need to store it, we just
289     * want the carry value */
290    uint64_t carry = 0;
291    for (int i = 0; i < BIGITS; i++)
292    {
293        for (int j = 0; j < i + 1; j++)
294            carry += (uint32_t)m_mantissa[BIGITS - 1 - j]
295                   * (uint32_t)x.m_mantissa[BIGITS - 1 + j - i];
296        carry >>= 16;
297    }
298
299    for (int i = 0; i < BIGITS; i++)
300    {
301        for (int j = i + 1; j < BIGITS; j++)
302            carry += (uint32_t)m_mantissa[BIGITS - 1 - j]
303                   * (uint32_t)x.m_mantissa[j - 1 - i];
304
305        carry += m_mantissa[BIGITS - 1 - i];
306        carry += x.m_mantissa[BIGITS - 1 - i];
307        ret.m_mantissa[BIGITS - 1 - i] = carry & 0xffffu;
308        carry >>= 16;
309    }
310
311    /* Renormalise in case we overflowed the mantissa */
312    if (carry)
313    {
314        carry--;
315        for (int i = 0; i < BIGITS; i++)
316        {
317            uint16_t tmp = ret.m_mantissa[i];
318            ret.m_mantissa[i] = (carry << 15) | (tmp >> 1);
319            carry = tmp & 0x0001u;
320        }
321        e++;
322    }
323
324    ret.m_signexp |= e + (1 << 30) - 1;
325
326    return ret;
327}
328
329real real::operator /(real const &x) const
330{
331    return *this * re(x);
332}
333
334real &real::operator +=(real const &x)
335{
336    real tmp = *this;
337    return *this = tmp + x;
338}
339
340real &real::operator -=(real const &x)
341{
342    real tmp = *this;
343    return *this = tmp - x;
344}
345
346real &real::operator *=(real const &x)
347{
348    real tmp = *this;
349    return *this = tmp * x;
350}
351
352real &real::operator /=(real const &x)
353{
354    real tmp = *this;
355    return *this = tmp / x;
356}
357
358real real::operator <<(int x) const
359{
360    real tmp = *this;
361    return tmp <<= x;
362}
363
364real real::operator >>(int x) const
365{
366    real tmp = *this;
367    return tmp >>= x;
368}
369
370real &real::operator <<=(int x)
371{
372    if (m_signexp << 1)
373        m_signexp += x;
374    return *this;
375}
376
377real &real::operator >>=(int x)
378{
379    if (m_signexp << 1)
380        m_signexp -= x;
381    return *this;
382}
383
384bool real::operator ==(real const &x) const
385{
386    if ((m_signexp << 1) == 0 && (x.m_signexp << 1) == 0)
387        return true;
388
389    if (m_signexp != x.m_signexp)
390        return false;
391
392    return memcmp(m_mantissa, x.m_mantissa, sizeof(m_mantissa)) == 0;
393}
394
395bool real::operator !=(real const &x) const
396{
397    return !(*this == x);
398}
399
400bool real::operator <(real const &x) const
401{
402    /* Ensure both numbers are positive */
403    if (m_signexp >> 31)
404        return (x.m_signexp >> 31) ? -*this > -x : true;
405
406    if (x.m_signexp >> 31)
407        return false;
408
409    /* Compare all relevant bits */
410    if (m_signexp != x.m_signexp)
411        return m_signexp < x.m_signexp;
412
413    for (int i = 0; i < BIGITS; i++)
414        if (m_mantissa[i] != x.m_mantissa[i])
415            return m_mantissa[i] < x.m_mantissa[i];
416
417    return false;
418}
419
420bool real::operator <=(real const &x) const
421{
422    return !(*this > x);
423}
424
425bool real::operator >(real const &x) const
426{
427    /* Ensure both numbers are positive */
428    if (m_signexp >> 31)
429        return (x.m_signexp >> 31) ? -*this < -x : false;
430
431    if (x.m_signexp >> 31)
432        return true;
433
434    /* Compare all relevant bits */
435    if (m_signexp != x.m_signexp)
436        return m_signexp > x.m_signexp;
437
438    for (int i = 0; i < BIGITS; i++)
439        if (m_mantissa[i] != x.m_mantissa[i])
440            return m_mantissa[i] > x.m_mantissa[i];
441
442    return false;
443}
444
445bool real::operator >=(real const &x) const
446{
447    return !(*this < x);
448}
449
450bool real::operator !() const
451{
452    return !(bool)*this;
453}
454
455real::operator bool() const
456{
457    /* A real is "true" if it is non-zero (exponent is non-zero) AND
458     * not NaN (exponent is not full bits OR higher order mantissa is zero) */
459    uint32_t exponent = m_signexp << 1;
460    return exponent && (~exponent || m_mantissa[0] == 0);
461}
462
463real re(real const &x)
464{
465    if (!(x.m_signexp << 1))
466    {
467        real ret = x;
468        ret.m_signexp = x.m_signexp | 0x7fffffffu;
469        ret.m_mantissa[0] = 0;
470        return ret;
471    }
472
473    /* Use the system's float inversion to approximate 1/x */
474    union { float f; uint32_t x; } u = { 1.0f }, v = { 1.0f };
475    v.x |= (uint32_t)x.m_mantissa[0] << 7;
476    v.x |= (uint32_t)x.m_mantissa[1] >> 9;
477    v.f = 1.0 / v.f;
478
479    real ret;
480    ret.m_mantissa[0] = (v.x >> 7) & 0xffffu;
481    ret.m_mantissa[1] = (v.x << 9) & 0xffffu;
482
483    uint32_t sign = x.m_signexp & 0x80000000u;
484    ret.m_signexp = sign;
485
486    int exponent = (x.m_signexp & 0x7fffffffu) + 1;
487    exponent = -exponent + (v.x >> 23) - (u.x >> 23);
488    ret.m_signexp |= (exponent - 1) & 0x7fffffffu;
489
490    /* FIXME: log2(BIGITS) steps of Newton-Raphson seems to be enough for
491     * convergence, but this hasn't been checked seriously. */
492    for (int i = 1; i < real::BIGITS; i *= 2)
493        ret = ret * (real::R_2 - ret * x);
494
495    return ret;
496}
497
498real sqrt(real const &x)
499{
500    /* if zero, return x */
501    if (!(x.m_signexp << 1))
502        return x;
503
504    /* if negative, return NaN */
505    if (x.m_signexp >> 31)
506    {
507        real ret;
508        ret.m_signexp = 0x7fffffffu;
509        ret.m_mantissa[0] = 0xffffu;
510        return ret;
511    }
512
513    /* Use the system's float inversion to approximate 1/sqrt(x). First
514     * we construct a float in the [1..4[ range that has roughly the same
515     * mantissa as our real. Its exponent is 0 or 1, depending on the
516     * partity of x. The final exponent is 0, -1 or -2. We use the final
517     * exponent and final mantissa to pre-fill the result. */
518    union { float f; uint32_t x; } u = { 1.0f }, v = { 2.0f };
519    v.x -= ((x.m_signexp & 1) << 23);
520    v.x |= (uint32_t)x.m_mantissa[0] << 7;
521    v.x |= (uint32_t)x.m_mantissa[1] >> 9;
522    v.f = 1.0 / sqrtf(v.f);
523
524    real ret;
525    ret.m_mantissa[0] = (v.x >> 7) & 0xffffu;
526    ret.m_mantissa[1] = (v.x << 9) & 0xffffu;
527
528    uint32_t sign = x.m_signexp & 0x80000000u;
529    ret.m_signexp = sign;
530
531    uint32_t exponent = (x.m_signexp & 0x7fffffffu);
532    exponent = ((1 << 30) + (1 << 29) - 1) - (exponent + 1) / 2;
533    exponent = exponent + (v.x >> 23) - (u.x >> 23);
534    ret.m_signexp |= exponent & 0x7fffffffu;
535
536    /* FIXME: log2(BIGITS) steps of Newton-Raphson seems to be enough for
537     * convergence, but this hasn't been checked seriously. */
538    for (int i = 1; i < real::BIGITS; i *= 2)
539    {
540        ret = ret * (real::R_3 - ret * ret * x);
541        ret.m_signexp--;
542    }
543
544    return ret * x;
545}
546
547real fabs(real const &x)
548{
549    real ret = x;
550    ret.m_signexp &= 0x7fffffffu;
551    return ret;
552}
553
554static real fast_log(real const &x)
555{
556    /* This fast log method is tuned to work on the [1..2] range and
557     * no effort whatsoever was made to improve convergence outside this
558     * domain of validity. It can converge pretty fast, provided we use
559     * the following variable substitutions:
560     *    y = sqrt(x)
561     *    z = (y - 1) / (y + 1)
562     *
563     * And the following identities:
564     *    ln(x) = 2 ln(y)
565     *          = 2 ln((1 + z) / (1 - z))
566     *          = 4 z (1 + z^2 / 3 + z^4 / 5 + z^6 / 7...)
567     *
568     * Any additional sqrt() call would halve the convergence time, but
569     * would also impact the final precision. For now we stick with one
570     * sqrt() call. */
571    real y = sqrt(x);
572    real z = (y - real::R_1) / (y + real::R_1), z2 = z * z, zn = z2;
573    real sum = real::R_1;
574
575    for (int i = 3; ; i += 2)
576    {
577        real newsum = sum + zn / (real)i;
578        if (newsum == sum)
579            break;
580        sum = newsum;
581        zn *= z2;
582    }
583
584    return z * (sum << 2);
585}
586
587real log(real const &x)
588{
589    /* Strategy for log(x): if x = 2^E*M then log(x) = E log(2) + log(M),
590     * with the property that M is in [1..2[, so fast_log() applies here. */
591    real tmp = x;
592    if (x.m_signexp >> 31 || x.m_signexp == 0)
593    {
594        tmp.m_signexp = 0xffffffffu;
595        tmp.m_mantissa[0] = 0xffffu;
596        return tmp;
597    }
598    tmp.m_signexp = (1 << 30) - 1;
599    return (real)(x.m_signexp - (1 << 30) + 1) * real::R_LN2 + fast_log(tmp);
600}
601
602real exp(real const &x)
603{
604    /* Strategy for exp(x): the Taylor series does not converge very fast
605     * with large positive or negative values.
606     *
607     * However, we know that the result is going to be in the form M*2^E,
608     * where M is the mantissa and E the exponent. We first try to predict
609     * a value for E, which is approximately log2(exp(x)) = x / log(2).
610     *
611     * Let E0 be an integer close to x / log(2). We need to find a value x0
612     * such that exp(x) = 2^E0 * exp(x0). We get x0 = x - E0 log(2).
613     *
614     * Thus the final algorithm:
615     *  int E0 = x / log(2)
616     *  real x0 = x - E0 log(2)
617     *  real x1 = exp(x0)
618     *  return x1 * 2^E0
619     */
620    int e0 = x / real::R_LN2;
621    real x0 = x - (real)e0 * real::R_LN2;
622    real x1 = real::R_1, fact = real::R_1, xn = x0;
623
624    for (int i = 1; ; i++)
625    {
626        fact *= (real)i;
627        real newx1 = x1 + xn / fact;
628        if (newx1 == x1)
629            break;
630        x1 = newx1;
631        xn *= x0;
632    }
633
634    x1.m_signexp += e0;
635    return x1;
636}
637
638real floor(real const &x)
639{
640    /* Strategy for floor(x):
641     *  - if negative, return -ceil(-x)
642     *  - if zero or negative zero, return x
643     *  - if less than one, return zero
644     *  - otherwise, if e is the exponent, clear all bits except the
645     *    first e. */
646    if (x < -real::R_0)
647        return -ceil(-x);
648    if (!x)
649        return x;
650    if (x < real::R_1)
651        return real::R_0;
652
653    real ret = x;
654    int exponent = x.m_signexp - (1 << 30) + 1;
655
656    for (int i = 0; i < real::BIGITS; i++)
657    {
658        if (exponent <= 0)
659            ret.m_mantissa[i] = 0;
660        else if (exponent < 8 * (int)sizeof(uint16_t))
661            ret.m_mantissa[i] &= ~((1 << (16 - exponent)) - 1);
662
663        exponent -= 8 * sizeof(uint16_t);
664    }
665
666    return ret;
667}
668
669real ceil(real const &x)
670{
671    /* Strategy for ceil(x):
672     *  - if negative, return -floor(-x)
673     *  - if x == floor(x), return x
674     *  - otherwise, return floor(x) + 1 */
675    if (x < -real::R_0)
676        return -floor(-x);
677    real ret = floor(x);
678    if (x == ret)
679        return ret;
680    else
681        return ret + real::R_1;
682}
683
684real round(real const &x)
685{
686    if (x < real::R_0)
687        return -round(-x);
688
689    return floor(x + (real::R_1 >> 1));
690}
691
692real fmod(real const &x, real const &y)
693{
694    if (!y)
695        return real::R_0; /* FIXME: return NaN */
696
697    if (!x)
698        return x;
699
700    real tmp = round(x / y);
701    return x - tmp * y;
702}
703
704real sin(real const &x)
705{
706    bool switch_sign = x.m_signexp & 0x80000000u;
707
708    real absx = fmod(fabs(x), real::R_PI << 1);
709    if (absx > real::R_PI)
710    {
711        absx -= real::R_PI;
712        switch_sign = !switch_sign;
713    }
714
715    if (absx > real::R_PI_2)
716        absx = real::R_PI - absx;
717
718    real ret = real::R_0, fact = real::R_1, xn = absx, x2 = absx * absx;
719    for (int i = 1; ; i += 2)
720    {
721        real newret = ret + xn / fact;
722        if (newret == ret)
723            break;
724        ret = newret;
725        xn *= x2;
726        fact *= (real)(-(i + 1) * (i + 2));
727    }
728
729    /* Propagate sign */
730    if (switch_sign)
731        ret.m_signexp ^= 0x80000000u;
732    return ret;
733}
734
735real cos(real const &x)
736{
737    return sin(real::R_PI_2 - x);
738}
739
740static real asinacos(real const &x, bool is_asin, bool is_negative)
741{
742    /* Strategy for asin(): in [-0.5..0.5], use a Taylor series around
743     * zero. In [0.5..1], use asin(x) = π/2 - 2*asin(sqrt((1-x)/2)), and
744     * in [-1..-0.5] just revert the sign.
745     * Strategy for acos(): use acos(x) = π/2 - asin(x) and try not to
746     * lose the precision around x=1. */
747    real absx = fabs(x);
748    bool around_zero = (absx < (real::R_1 >> 1));
749
750    if (!around_zero)
751        absx = sqrt((real::R_1 - absx) >> 1);
752
753    real ret = absx, xn = absx, x2 = absx * absx, fact1 = 2, fact2 = 1;
754    for (int i = 1; ; i++)
755    {
756        xn *= x2;
757        real mul = (real)(2 * i + 1);
758        real newret = ret + ((fact1 * xn / (mul * fact2)) >> (i * 2));
759        if (newret == ret)
760            break;
761        ret = newret;
762        fact1 *= (real)((2 * i + 1) * (2 * i + 2));
763        fact2 *= (real)((i + 1) * (i + 1));
764    }
765
766    if (is_negative)
767        ret = -ret;
768
769    if (around_zero)
770        ret = is_asin ? ret : real::R_PI_2 - ret;
771    else
772    {
773        real adjust = is_negative ? real::R_PI : real::R_0;
774        if (is_asin)
775            ret = real::R_PI_2 - adjust - (ret << 1);
776        else
777            ret = adjust + (ret << 1);
778    }
779
780    return ret;
781}
782
783real asin(real const &x)
784{
785    return asinacos(x, true, x.m_signexp >> 31);
786}
787
788real acos(real const &x)
789{
790    return asinacos(x, false, x.m_signexp >> 31);
791}
792
793real atan(real const &x)
794{
795    /* Computing atan(x): we choose a different Taylor series depending on
796     * the value of x to help with convergence.
797     *
798     * If |x| < 0.5 we evaluate atan(y) near 0:
799     *  atan(y) = y - y^3/3 + y^5/5 - y^7/7 + y^9/9 ...
800     *
801     * If 0.5 <= |x| < 1.5 we evaluate atan(1+y) near 0:
802     *  atan(1+y) = π/4 + y/(1*2^1) - y^2/(2*2^1) + y^3/(3*2^2)
803     *                  - y^5/(5*2^3) + y^6/(6*2^3) - y^7/(7*2^4)
804     *                  + y^9/(9*2^5) - y^10/(10*2^5) + y^11/(11*2^6) ...
805     *
806     * If 1.5 <= |x| < 2 we evaluate atan(sqrt(3)+2y) near 0:
807     *  atan(sqrt(3)+2y) = π/3 + 1/2 y - sqrt(3)/2 y^2/2
808     *                         + y^3/3 - sqrt(3)/2 y^4/4 + 1/2 y^5/5
809     *                         - 1/2 y^7/7 + sqrt(3)/2 y^8/8
810     *                         - y^9/9 + sqrt(3)/2 y^10/10 - 1/2 y^11/11
811     *                         + 1/2 y^13/13 - sqrt(3)/2 y^14/14
812     *                         + y^15/15 - sqrt(3)/2 y^16/16 + 1/2 y^17/17 ...
813     *
814     * If |x| >= 2 we evaluate atan(y) near +∞:
815     *  atan(y) = π/2 - y^-1 + y^-3/3 - y^-5/5 + y^-7/7 - y^-9/9 ...
816     */
817    real absx = fabs(x);
818
819    if (absx < (real::R_1 >> 1))
820    {
821        real ret = x, xn = x, mx2 = -x * x;
822        for (int i = 3; ; i += 2)
823        {
824            xn *= mx2;
825            real newret = ret + xn / (real)i;
826            if (newret == ret)
827                break;
828            ret = newret;
829        }
830        return ret;
831    }
832
833    real ret = 0;
834
835    if (absx < (real::R_3 >> 1))
836    {
837        real y = real::R_1 - absx;
838        real yn = y, my2 = -y * y;
839        for (int i = 0; ; i += 2)
840        {
841            real newret = ret + ((yn / (real)(2 * i + 1)) >> (i + 1));
842            yn *= y;
843            newret += (yn / (real)(2 * i + 2)) >> (i + 1);
844            yn *= y;
845            newret += (yn / (real)(2 * i + 3)) >> (i + 2);
846            if (newret == ret)
847                break;
848            ret = newret;
849            yn *= my2;
850        }
851        ret = real::R_PI_4 - ret;
852    }
853    else if (absx < real::R_2)
854    {
855        real y = (absx - real::R_SQRT3) >> 1;
856        real yn = y, my2 = -y * y;
857        for (int i = 1; ; i += 6)
858        {
859            real newret = ret + ((yn / (real)i) >> 1);
860            yn *= y;
861            newret -= (real::R_SQRT3 >> 1) * yn / (real)(i + 1);
862            yn *= y;
863            newret += yn / (real)(i + 2);
864            yn *= y;
865            newret -= (real::R_SQRT3 >> 1) * yn / (real)(i + 3);
866            yn *= y;
867            newret += (yn / (real)(i + 4)) >> 1;
868            if (newret == ret)
869                break;
870            ret = newret;
871            yn *= my2;
872        }
873        ret = real::R_PI_3 + ret;
874    }
875    else
876    {
877        real y = re(absx);
878        real yn = y, my2 = -y * y;
879        ret = y;
880        for (int i = 3; ; i += 2)
881        {
882            yn *= my2;
883            real newret = ret + yn / (real)i;
884            if (newret == ret)
885                break;
886            ret = newret;
887        }
888        ret = real::R_PI_2 - ret;
889    }
890
891    /* Propagate sign */
892    ret.m_signexp |= (x.m_signexp & 0x80000000u);
893    return ret;
894}
895
896void real::print(int ndigits) const
897{
898    real const r1 = 1, r10 = 10;
899    real x = *this;
900
901    if (x.m_signexp >> 31)
902    {
903        printf("-");
904        x = -x;
905    }
906
907    /* Normalise x so that mantissa is in [1..9.999] */
908    int exponent = 0;
909    if (x.m_signexp)
910    {
911        for (real div = r1, newdiv; true; div = newdiv)
912        {
913            newdiv = div * r10;
914            if (x < newdiv)
915            {
916                x /= div;
917                break;
918            }
919            exponent++;
920        }
921        for (real mul = 1, newx; true; mul *= r10)
922        {
923            newx = x * mul;
924            if (newx >= r1)
925            {
926                x = newx;
927                break;
928            }
929            exponent--;
930        }
931    }
932
933    /* Print digits */
934    for (int i = 0; i < ndigits; i++)
935    {
936        int digit = (int)x;
937        printf("%i", digit);
938        if (i == 0)
939            printf(".");
940        x -= real(digit);
941        x *= r10;
942    }
943
944    /* Print exponent information */
945    if (exponent < 0)
946        printf("e-%i", -exponent);
947    else if (exponent > 0)
948        printf("e+%i", exponent);
949
950    printf("\n");
951}
952
953static real fast_pi()
954{
955    /* Approximate Pi using Machin's formula: 16*atan(1/5)-4*atan(1/239) */
956    real ret = 0.0, x0 = 5.0, x1 = 239.0;
957    real const m0 = -x0 * x0, m1 = -x1 * x1, r16 = 16.0, r4 = 4.0;
958
959    for (int i = 1; ; i += 2)
960    {
961        real newret = ret + r16 / (x0 * (real)i) - r4 / (x1 * (real)i);
962        if (newret == ret)
963            break;
964        ret = newret;
965        x0 *= m0;
966        x1 *= m1;
967    }
968
969    return ret;
970}
971
972real const real::R_0        = (real)0.0;
973real const real::R_1        = (real)1.0;
974real const real::R_2        = (real)2.0;
975real const real::R_3        = (real)3.0;
976real const real::R_10       = (real)10.0;
977
978real const real::R_LN2      = fast_log(R_2);
979real const real::R_LN10     = log(R_10);
980real const real::R_LOG2E    = re(R_LN2);
981real const real::R_LOG10E   = re(R_LN10);
982real const real::R_E        = exp(R_1);
983real const real::R_PI       = fast_pi();
984real const real::R_PI_2     = R_PI >> 1;
985real const real::R_PI_3     = R_PI / R_3;
986real const real::R_PI_4     = R_PI >> 2;
987real const real::R_1_PI     = re(R_PI);
988real const real::R_2_PI     = R_1_PI << 1;
989real const real::R_2_SQRTPI = re(sqrt(R_PI)) << 1;
990real const real::R_SQRT2    = sqrt(R_2);
991real const real::R_SQRT3    = sqrt(R_3);
992real const real::R_SQRT1_2  = R_SQRT2 >> 1;
993
994} /* namespace lol */
995
Note: See TracBrowser for help on using the repository browser.