after multiple objections of libtom users [1], we decided to change licensing
[libtomfloat.git] / mpf_exp.c
blobed2bb54b963d0612b2a02610974c172339422c14
1 /* LibTomFloat, multiple-precision floating-point library
3 * LibTomFloat is a library that provides multiple-precision
4 * floating-point artihmetic as well as trigonometric functionality.
6 * This library requires the public domain LibTomMath to be installed.
7 *
8 * This library is free for all purposes without any express
9 * gurantee it works
11 * Tom St Denis, tomstdenis@iahu.ca, http://float.libtomcrypt.org
13 #include <tomfloat.h>
16 /* compute b = e^a using e^x == \sum_{n=0}^{\infty} {1 \over n!}x^n */
17 int mpf_exp(mp_float *a, mp_float *b)
19 mp_float oldval, tmpx, tmpovern, tmp, res;
20 int err, itts;
21 long n;
23 /* initialize temps */
24 if ((err = mpf_init_multi(b->radix, &oldval, &tmpx, &tmpovern, &tmp, &res, NULL)) != MP_OKAY) {
25 return err;
28 /* initlialize temps */
29 /* all three start at one */
30 if ((err = mpf_const_d(&res, 1)) != MP_OKAY) { goto __ERR; }
31 if ((err = mpf_const_d(&tmpovern, 1)) != MP_OKAY) { goto __ERR; }
32 if ((err = mpf_const_d(&tmpx, 1)) != MP_OKAY) { goto __ERR; }
33 n = 1;
35 /* get number of iterations */
36 itts = mpf_iterations(b);
38 while (itts-- > 0) {
39 if ((err = mpf_copy(&res, &oldval)) != MP_OKAY) { goto __ERR; }
41 /* compute 1/n! as 1/(n-1)! * 1/n */
42 if ((err = mpf_const_d(&tmp, n++)) != MP_OKAY) { goto __ERR; }
43 if ((err = mpf_inv(&tmp, &tmp)) != MP_OKAY) { goto __ERR; }
44 if ((err = mpf_mul(&tmp, &tmpovern, &tmpovern)) != MP_OKAY) { goto __ERR; }
46 /* compute x^n as x^(n-1) * x */
47 if ((err = mpf_mul(&tmpx, a, &tmpx)) != MP_OKAY) { goto __ERR; }
49 /* multiply and sum them */
50 if ((err = mpf_mul(&tmpovern, &tmpx, &tmp)) != MP_OKAY) { goto __ERR; }
51 if ((err = mpf_add(&tmp, &res, &res)) != MP_OKAY) { goto __ERR; }
53 if (mpf_cmp(&oldval, &res) == MP_EQ) {
54 break;
58 mpf_exch(&res, b);
59 __ERR: mpf_clear_multi(&oldval, &tmpx, &tmpovern, &tmp, &res, NULL);
60 return err;