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.
8 * This library is free for all purposes without any express
11 * Tom St Denis, tomstdenis@iahu.ca, http://float.libtomcrypt.org
17 Using the newton approximation y1 = y - (e^y - x)/e^y
19 Which converges quickly and we can reuse e^y so we only calc it once per loop
22 int mpf_ln(mp_float
*a
, mp_float
*b
)
24 mp_float oldval
, tmpey
, tmpy
, val
;
29 if (a
->mantissa
.sign
== MP_NEG
) {
34 if (mpf_iszero(a
) == MP_YES
) {
35 return mpf_const_d(b
, 1);
38 /* initialize temps */
39 if ((err
= mpf_init_multi(b
->radix
, &oldval
, &tmpey
, &tmpy
, &val
, NULL
)) != MP_OKAY
) {
44 if ((err
= mpf_const_e(&val
)) != MP_OKAY
) { goto __ERR
; }
45 if ((err
= mpf_sqr(&val
, &val
)) != MP_OKAY
) { goto __ERR
; }
46 if ((err
= mpf_inv(&val
, &tmpey
)) != MP_OKAY
) { goto __ERR
; }
47 if ((err
= mpf_copy(a
, &tmpy
)) != MP_OKAY
) { goto __ERR
; }
48 if ((err
= mpf_normalize_to(&tmpy
, b
->radix
)) != MP_OKAY
) { goto __ERR
; }
52 while (mpf_cmp(&tmpy
, &val
) == MP_GT
) {
54 if ((err
= mpf_mul(&tmpy
, &tmpey
, &tmpy
)) != MP_OKAY
) { goto __ERR
; }
56 if ((err
= mpf_const_d(&tmpy
, k
*2)) != MP_OKAY
) { goto __ERR
; }
58 /* number of iterations */
59 itts
= mpf_iterations(b
);
62 if ((err
= mpf_copy(&tmpy
, &oldval
)) != MP_OKAY
) { goto __ERR
; }
64 /* get e^y and save it */
65 if ((err
= mpf_exp(&tmpy
, &tmpey
)) != MP_OKAY
) { goto __ERR
; }
67 /* now compute e^y - x */
68 if ((err
= mpf_sub(&tmpey
, a
, &val
)) != MP_OKAY
) { goto __ERR
; }
70 /* now compute (e^y - x) / e^y */
71 if ((err
= mpf_div(&val
, &tmpey
, &val
)) != MP_OKAY
) { goto __ERR
; }
73 /* y = y - (e^y - x)/e^y */
74 if ((err
= mpf_sub(&tmpy
, &val
, &tmpy
)) != MP_OKAY
) { goto __ERR
; }
76 if (mpf_cmp(&tmpy
, &oldval
) == MP_EQ
) {
81 __ERR
: mpf_clear_multi(&oldval
, &tmpey
, &tmpy
, &val
, NULL
);