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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
use core::convert::TryInto;
use crate::{
error::{assert_finite, assert_limited_precision, panic_power_negative_base},
fbig::FBig,
repr::{Context, Repr, Word},
round::{Round, Rounded},
};
use dashu_base::{Approximation::*, BitTest, DivRemEuclid, EstimatedLog2, Sign};
use dashu_int::IBig;
impl<R: Round, const B: Word> FBig<R, B> {
/// Raise the floating point number to an integer power.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// let a = DBig::from_str_native("-1.234")?;
/// assert_eq!(a.powi(10.into()), DBig::from_str_native("8.188")?);
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn powi(&self, exp: IBig) -> FBig<R, B> {
self.context.powi(&self.repr, exp).value()
}
/// Raise the floating point number to an floating point power.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// let x = DBig::from_str_native("1.23")?;
/// let y = DBig::from_str_native("-4.56")?;
/// assert_eq!(x.powf(&y), DBig::from_str_native("0.389")?);
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn powf(&self, exp: &Self) -> Self {
let context = Context::max(self.context, exp.context);
context.powf(&self.repr, &exp.repr).value()
}
/// Calculate the exponential function (`eˣ`) on the floating point number.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// let a = DBig::from_str_native("-1.234")?;
/// assert_eq!(a.exp(), DBig::from_str_native("0.2911")?);
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn exp(&self) -> FBig<R, B> {
self.context.exp(&self.repr).value()
}
/// Calculate the exponential minus one function (`eˣ-1`) on the floating point number.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// let a = DBig::from_str_native("-0.1234")?;
/// assert_eq!(a.exp_m1(), DBig::from_str_native("-0.11609")?);
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn exp_m1(&self) -> FBig<R, B> {
self.context.exp_m1(&self.repr).value()
}
}
// TODO: give the exact formulation of required guard bits
impl<R: Round> Context<R> {
/// Raise the floating point number to an integer power under this context.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// use dashu_base::Approximation::*;
/// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
///
/// let context = Context::<HalfAway>::new(2);
/// let a = DBig::from_str_native("-1.234")?;
/// assert_eq!(context.powi(&a.repr(), 10.into()), Inexact(DBig::from_str_native("8.2")?, AddOne));
/// # Ok::<(), ParseError>(())
/// ```
///
/// # Panics
///
/// Panics if the precision is unlimited and the exponent is negative. In this case, the exact
/// result is likely to have infinite digits.
pub fn powi<const B: Word>(&self, base: &Repr<B>, exp: IBig) -> Rounded<FBig<R, B>> {
assert_finite(base);
let (exp_sign, exp) = exp.into_parts();
if exp_sign == Sign::Negative {
// if the exponent is negative, then negate the exponent
// note that do the inverse at last requires less guard bits
assert_limited_precision(self.precision); // TODO: we can allow this if the inverse is exact (only when significand is one?)
let guard_bits = self.precision.bit_len() * 2; // heuristic
let rev_context = Context::<R::Reverse>::new(self.precision + guard_bits);
let pow = rev_context.powi(base, exp.into()).value();
let inv = rev_context.repr_div(Repr::one(), pow.repr);
let repr = inv.and_then(|v| self.repr_round(v));
return repr.map(|v| FBig::new(v, *self));
}
if exp.is_zero() {
return Exact(FBig::ONE);
} else if exp.is_one() {
let repr = self.repr_round_ref(base);
return repr.map(|v| FBig::new(v, *self));
}
let work_context = if self.is_limited() {
// increase working precision when the exponent is large
let guard_digits = exp.bit_len() + self.precision.bit_len(); // heuristic
Context::<R>::new(self.precision + guard_digits)
} else {
Context::<R>::new(0)
};
// binary exponentiation from left to right
let mut p = exp.bit_len() - 2;
let mut res = work_context.square(base);
loop {
if exp.bit(p) {
res = res.and_then(|v| work_context.mul(v.repr(), base));
}
if p == 0 {
break;
}
p -= 1;
res = res.and_then(|v| work_context.square(v.repr()));
}
res.and_then(|v| v.with_precision(self.precision))
}
/// Raise the floating point number to an floating point power under this context.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// use dashu_base::Approximation::*;
/// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
///
/// let context = Context::<HalfAway>::new(2);
/// let x = DBig::from_str_native("1.23")?;
/// let y = DBig::from_str_native("-4.56")?;
/// assert_eq!(context.powf(&x.repr(), &y.repr()), Inexact(DBig::from_str_native("0.39")?, AddOne));
/// # Ok::<(), ParseError>(())
/// ```
///
/// # Panics
///
/// Panics if the precision is unlimited.
pub fn powf<const B: Word>(&self, base: &Repr<B>, exp: &Repr<B>) -> Rounded<FBig<R, B>> {
assert_finite(base);
assert_limited_precision(self.precision); // TODO: we can allow it if exp is integer
// shortcuts
if exp.is_zero() {
return Exact(FBig::ONE);
} else if exp.is_one() {
let repr = self.repr_round_ref(base);
return repr.map(|v| FBig::new(v, *self));
}
if base.sign() == Sign::Negative {
// TODO: we should allow negative base when exp is an integer
panic_power_negative_base()
}
// x^y = exp(y*ln(x)), use a simple rule for guard bits
let guard_digits = 10 + self.precision.log2_est() as usize;
let work_context = Context::<R>::new(self.precision + guard_digits);
let res = work_context
.ln(base)
.and_then(|v| work_context.mul(&v.repr, exp))
.and_then(|v| work_context.exp(&v.repr));
res.and_then(|v| v.with_precision(self.precision))
}
/// Calculate the exponential function (`eˣ`) on the floating point number under this context.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// use dashu_base::Approximation::*;
/// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
///
/// let context = Context::<HalfAway>::new(2);
/// let a = DBig::from_str_native("-1.234")?;
/// assert_eq!(context.exp(&a.repr()), Inexact(DBig::from_str_native("0.29")?, NoOp));
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn exp<const B: Word>(&self, x: &Repr<B>) -> Rounded<FBig<R, B>> {
self.exp_internal(x, false)
}
/// Calculate the exponential minus one function (`eˣ-1`) on the floating point number under this context.
///
/// # Examples
///
/// ```
/// # use dashu_base::ParseError;
/// # use dashu_float::DBig;
/// use dashu_base::Approximation::*;
/// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
///
/// let context = Context::<HalfAway>::new(2);
/// let a = DBig::from_str_native("-0.1234")?;
/// assert_eq!(context.exp_m1(&a.repr()), Inexact(DBig::from_str_native("-0.12")?, SubOne));
/// # Ok::<(), ParseError>(())
/// ```
#[inline]
pub fn exp_m1<const B: Word>(&self, x: &Repr<B>) -> Rounded<FBig<R, B>> {
self.exp_internal(x, true)
}
// TODO: change reduction to (x - s log2) / 2ⁿ, so that the final powering is always base 2, and doesn't depends on powi.
// the powering exp(r)^(2ⁿ) could be optimized by noticing (1+x)^2 - 1 = x^2 + 2x
// consider this change after having a benchmark
fn exp_internal<const B: Word>(&self, x: &Repr<B>, minus_one: bool) -> Rounded<FBig<R, B>> {
assert_finite(x);
assert_limited_precision(self.precision);
if x.is_zero() {
return match minus_one {
false => Exact(FBig::ONE),
true => Exact(FBig::ZERO),
};
}
// A simple algorithm:
// - let r = (x - s logB) / Bⁿ, where s = floor(x / logB), such that r < B⁻ⁿ.
// - if the target precision is p digits, then there're only about p/m terms in Tyler series
// - finally, exp(x) = Bˢ * exp(r)^(Bⁿ)
// - the optimal n is √p as given by MPFR
// Maclaurin series: exp(r) = 1 + Σ(rⁱ/i!)
// There will be about p/log_B(r) summations when calculating the series, to prevent
// loss of significant, we needs about log_B(p) guard digits.
let series_guard_digits = (self.precision.log2_est() / B.log2_est()) as usize + 2;
let pow_guard_digits = (self.precision.bit_len() as f32 * B.log2_est() * 2.) as usize; // heuristic
let work_precision;
// When minus_one is true and |x| < 1/B, the input is fed into the Maclaurin series without scaling
let no_scaling = minus_one && x.log2_est() < -B.log2_est();
let (s, n, r) = if no_scaling {
// if minus_one is true and x is already small (x < 1/B),
// then directly evaluate the Maclaurin series without scaling
if x.sign() == Sign::Negative {
// extra digits are required to prevent cancellation during the summation
work_precision = self.precision + 2 * series_guard_digits;
} else {
work_precision = self.precision + series_guard_digits;
}
let context = Context::<R>::new(work_precision);
(0, 0, FBig::new(context.repr_round_ref(x).value(), context))
} else {
work_precision = self.precision + series_guard_digits + pow_guard_digits;
let context = Context::<R>::new(work_precision);
let x = FBig::new(context.repr_round_ref(x).value(), context);
let logb = context.ln_base::<B>();
let (s, r) = x.div_rem_euclid(logb);
// here m is roughly equal to sqrt(self.precision)
let n = 1usize << (self.precision.bit_len() / 2);
let s: isize = s.try_into().expect("exponent is too large");
(s, n, r)
};
let r = r >> n as isize;
let mut factorial = IBig::ONE;
let mut pow = r.clone();
let mut sum = if no_scaling {
r.clone()
} else {
FBig::ONE + &r
};
let mut k = 2;
loop {
factorial *= k;
pow *= &r;
// TODO: use &pow / &factorial < ulp as stop criteria?
let next = &sum + &pow / &factorial;
if next == sum {
break;
}
sum = next;
k += 1;
}
if no_scaling {
sum.with_precision(self.precision)
} else if minus_one {
// add extra digits to compensate for the subtraction
Context::<R>::new(self.precision + self.precision / 8 + 1) // heuristic
.powi(sum.repr(), Repr::<B>::BASE.pow(n))
.map(|v| (v << s) - FBig::ONE)
.and_then(|v| v.with_precision(self.precision))
} else {
self.powi(sum.repr(), Repr::<B>::BASE.pow(n))
.map(|v| v << s)
}
}
}