mpf_exp.c

来自「精确小数算法库,可以实现任意长度的精确小数算法,用c语言实现,主要用于密码学中小」· C语言 代码 · 共 63 行

C
63
字号
/* LibTomFloat, multiple-precision floating-point library * * LibTomFloat is a library that provides multiple-precision * floating-point artihmetic as well as trigonometric functionality. * * This library requires the public domain LibTomMath to be installed. *  * This library is free for all purposes without any express * gurantee it works * * Tom St Denis, tomstdenis@iahu.ca, http://float.libtomcrypt.org */#include <tomfloat.h>/* compute b = e^a using e^x == \sum_{n=0}^{\infty} {1 \over n!}x^n */int  mpf_exp(mp_float *a, mp_float *b){   mp_float  oldval, tmpx, tmpovern, tmp, res;    int       err, itts;   long      n;   /* initialize temps */   if ((err = mpf_init_multi(b->radix, &oldval, &tmpx, &tmpovern, &tmp, &res, NULL)) != MP_OKAY) {      return err;   }   /* initlialize temps */   /* all three start at one */   if ((err = mpf_const_d(&res, 1)) != MP_OKAY)                                         { goto __ERR; }   if ((err = mpf_const_d(&tmpovern, 1)) != MP_OKAY)                                    { goto __ERR; }   if ((err = mpf_const_d(&tmpx, 1)) != MP_OKAY)                                        { goto __ERR; }   n = 1;   /* get number of iterations */   itts = mpf_iterations(b);   while (itts-- > 0) {       if ((err = mpf_copy(&res, &oldval)) != MP_OKAY)                                  { goto __ERR; }       /* compute 1/n! as 1/(n-1)! * 1/n */       if ((err = mpf_const_d(&tmp, n++)) != MP_OKAY)                                   { goto __ERR; }       if ((err = mpf_inv(&tmp, &tmp)) != MP_OKAY)                                      { goto __ERR; }       if ((err = mpf_mul(&tmp, &tmpovern, &tmpovern)) != MP_OKAY)                      { goto __ERR; }        /* compute x^n as x^(n-1) * x */       if ((err = mpf_mul(&tmpx, a, &tmpx)) != MP_OKAY)                                 { goto __ERR; }       /* multiply and sum them */       if ((err = mpf_mul(&tmpovern, &tmpx, &tmp)) != MP_OKAY)                          { goto __ERR; }       if ((err = mpf_add(&tmp, &res, &res)) != MP_OKAY)                                { goto __ERR; }       if (mpf_cmp(&oldval, &res) == MP_EQ) {          break;       }   }   mpf_exch(&res, b);__ERR: mpf_clear_multi(&oldval, &tmpx, &tmpovern, &tmp, &res, NULL);   return err;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?