1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use crate::base::*;
use crate::consts::LN_2;

// 1/ln(2)
const FRAC_1_LN_2: TwoFloat = TwoFloat {
    hi: 1.4426950408889634,
    lo: 2.0355273740931033e-17,
};

// ln(10)
const LN_10: TwoFloat = TwoFloat {
    hi: 2.302585092994046,
    lo: -2.1707562233822494e-16,
};

// limits
const EXP_UPPER_LIMIT: f64 = 709.782712893384;
const EXP_LOWER_LIMIT: f64 = -745.1332191019412;

// Coefficients for polynomial approximation of x*(exp(x)+1)/(exp(x)-1)

const P1: TwoFloat = TwoFloat {
    hi: 0.16666666666666666,
    lo: 8.301559840894034e-18,
};
const P2: TwoFloat = TwoFloat {
    hi: -0.0027777777777776512,
    lo: 1.1664268064351513e-19,
};
const P3: TwoFloat = TwoFloat {
    hi: 6.613756613123634e-05,
    lo: 3.613966532258593e-21,
};
const P4: TwoFloat = TwoFloat {
    hi: -1.6534390027595268e-06,
    lo: 2.6408090483313454e-23,
};
const P5: TwoFloat = TwoFloat {
    hi: 4.175167193059256e-08,
    lo: -2.949837910669653e-24,
};
const P6: TwoFloat = TwoFloat {
    hi: -1.0456596683715461e-09,
    lo: -9.375356618962057e-26,
};

fn mul_pow2(mut x: f64, mut y: i32) -> f64 {
    loop {
        if y < -1074 {
            x *= f64::from_bits(1u64);
            y += 1074;
        } else if y < -1022 {
            return x * f64::from_bits(1u64 << (y + 1074));
        } else if y < 1024 {
            return x * f64::from_bits(((y + 1023) as u64) << 52);
        } else {
            x *= f64::from_bits(0x7fe << 52);
            y -= 1023;
        }
    }
}

impl TwoFloat {
    /// Returns `e^(self)`, (the exponential function).
    ///
    /// Note that this function returns an approximate value, in particular
    /// the low word of the core polynomial approximation is not guaranteed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use twofloat::TwoFloat;
    /// let a = TwoFloat::from(2.0);
    /// let b = a.exp();
    /// let e2 = twofloat::consts::E * twofloat::consts::E;
    ///
    /// assert!((b - e2).abs() / e2 < 1e-16);
    pub fn exp(&self) -> TwoFloat {
        if self.hi <= EXP_LOWER_LIMIT {
            TwoFloat::from(0.0)
        } else if self.hi >= EXP_UPPER_LIMIT {
            TwoFloat {
                hi: std::f64::INFINITY,
                lo: 0.0,
            }
        } else if self.hi == 0.0 {
            TwoFloat::from(1.0)
        } else {
            // reduce value to range |r| <= ln(2)/2
            // where self = k*ln(2) + r

            let k = ((FRAC_1_LN_2 * self).hi + 0.5).trunc();
            let r = self - LN_2 * k;

            // Now approximate the function
            //
            // R(r^2) = r*(exp(r)+1)/(exp(r)-1) = 2 + P1*r^2 + P2*r^4 + ...
            //
            // using a polynomial obtained by the Remez algorithm on the
            // interval [0, ln(2)/2], then:
            //
            // exp(r) = 1 + 2*r/(R-r) = 1 + r + (r*R1) / (2-R1)
            //
            // where R1 = r - (P1*r^2 + P2*r^4 + ...)

            let rr = &r * &r;
            let r1 = &r - &rr * (P1 + &rr * (P2 + &rr * (P3 + &rr * (P4 + &rr * (P5 + &rr * P6)))));

            let exp_r = 1.0 - ((&r * &r1) / (&r1 - 2.0) - &r);

            // then scale back

            if k == 0.0 {
                exp_r
            } else {
                TwoFloat {
                    hi: mul_pow2(exp_r.hi, k as i32),
                    lo: mul_pow2(exp_r.lo, k as i32),
                }
            }
        }
    }

    /// Returns `2^(self)`.
    ///
    /// This is a convenience method that computes `(self * LN_2).exp()`, no
    /// additional accuracy is provided.
    ///
    /// # Examples
    ///
    /// ```
    /// # use twofloat::TwoFloat;
    /// let a = TwoFloat::from(6.0).exp2();
    ///
    /// assert!((a - 64.0).abs() < 1e-15);
    pub fn exp2(&self) -> TwoFloat {
        (self * LN_2).exp()
    }

    /// Returns the natural logarithm of the value.
    ///
    /// Uses Newton–Raphson iteration which depends on the `exp` function, so
    /// may not be fully accurate to the full precision of a `TwoFloat`.
    ///
    /// # Example
    ///
    /// ```
    /// let a = twofloat::consts::E.ln();
    /// assert!((a - 1.0).abs() < 1e-11);
    pub fn ln(&self) -> TwoFloat {
        if *self == 1.0 {
            TwoFloat::from(0.0)
        } else if *self <= 0.0 {
            TwoFloat {
                hi: std::f64::NAN,
                lo: std::f64::NAN,
            }
        } else {
            let mut x = TwoFloat::from(self.hi.ln());
            x += self * (-x).exp() - 1.0;
            x + self * (-x).exp() - 1.0
        }
    }

    /// Returns the logarithm of the number with respect to an arbitrary base.
    ///
    /// This is a convenience method that computes `self.ln() / base.ln()`, no
    /// additional accuracy is provided.
    ///
    /// # Examples
    ///
    /// let a = TwoFloat::from(81.0);
    /// let b = TwoFloat::from(3.0);
    /// let c = a.log(&b);
    ///
    /// assert!((c - 4.0).abs() < 1e-12);
    pub fn log(&self, base: &TwoFloat) -> TwoFloat {
        self.ln() / base.ln()
    }

    /// Returns the base 2 logarithm of the number.
    ///
    /// This is a convenience method that computes `self.ln() / LN_2`, no
    /// additional accuracy is provided.
    ///
    /// # Examples
    ///
    /// ```
    /// # use twofloat::TwoFloat;
    /// let a = TwoFloat::from(64.0).log2();
    ///
    /// assert!((a - 6.0).abs() < 1e-12, "{}", a);
    pub fn log2(&self) -> TwoFloat {
        self.ln() / LN_2
    }

    /// Returns the base 10 logarithm of the number.
    ///
    /// This is a convenience method that computes `self.ln() / LN_10`, no
    /// additional accuracy is provided.
    ///
    /// # Examples
    ///
    /// ```
    /// # use twofloat::TwoFloat;
    /// let a = TwoFloat::from(100.0).log10();
    ///
    /// assert!((a - 2.0).abs() < 1e-12);
    pub fn log10(&self) -> TwoFloat {
        self.ln() / LN_10
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::*;

    use rand::Rng;

    #[test]
    fn exp_test() {
        let mut rng = rand::thread_rng();
        let src_dist = rand::distributions::Uniform::new(-600.0, EXP_UPPER_LIMIT);

        assert_eq!(
            TwoFloat::from(-1000.0).exp(),
            0.0,
            "Large negative exponent produced non-zero value"
        );
        assert!(
            !TwoFloat::from(1000.0).exp().is_valid(),
            "Large positive exponent produced valid value"
        );

        for i in 0..TEST_ITERS {
            let a = match i {
                0 => 0.0,
                1 => -600.0,
                _ => rng.sample(src_dist),
            };
            let b = TwoFloat::from(a);

            let exp_a = a.exp();
            let exp_b = b.exp();

            assert!(
                no_overlap(exp_b.hi, exp_b.lo),
                "Overlap detected in exp({}) = {:?}",
                a,
                exp_b
            );

            let difference = ((exp_b - exp_a) / exp_a).abs();

            assert!(
                difference < 1e-10,
                "Mismatch in exp({}): {} vs {:?}",
                a,
                exp_a,
                exp_b
            );
        }
    }

    #[test]
    fn ln_test() {
        let mut rng = rand::thread_rng();
        let src_dist = rand::distributions::Uniform::new(f64::from_bits(1u64), std::f64::MAX);

        assert!(
            !TwoFloat::from(0.0).ln().is_valid(),
            "ln(0) produced valid result"
        );
        assert!(
            !TwoFloat::from(-5.0).ln().is_valid(),
            "ln(negative) produced valid result"
        );

        for i in 0..TEST_ITERS {
            let a = match i {
                0 => 1.0,
                1 => std::f64::MAX,
                _ => rng.sample(src_dist),
            };
            let b = TwoFloat::from(a);

            let ln_a = a.ln();
            let ln_b = b.ln();

            assert!(
                no_overlap(ln_b.hi, ln_b.lo),
                "Overlap detected in ln({}) = {:?}",
                a,
                ln_a
            );

            let difference = (ln_b - ln_a).abs();

            assert!(
                difference < 1e-10,
                "Mismatch in ln({}): {} vs {:?}",
                a,
                ln_a,
                ln_b
            );
        }
    }
}