Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
GenericPacketMathFunctions.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2007 Julien Pommier
5// Copyright (C) 2014 Pedro Gonnet (pedro.gonnet@gmail.com)
6// Copyright (C) 2009-2019 Gael Guennebaud <gael.guennebaud@inria.fr>
7// Copyright (C) 2018-2025 Rasmus Munk Larsen <rmlarsen@gmail.com>
8//
9// This Source Code Form is subject to the terms of the Mozilla
10// Public License v. 2.0. If a copy of the MPL was not distributed
11// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
12// SPDX-License-Identifier: MPL-2.0
13
14/* The exp and log functions of this file initially come from
15 * Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
16 */
17
18#ifndef EIGEN_ARCH_GENERIC_PACKET_MATH_FUNCTIONS_H
19#define EIGEN_ARCH_GENERIC_PACKET_MATH_FUNCTIONS_H
20
21// IWYU pragma: private
22#include "../../InternalHeaderCheck.h"
23#include "GenericPacketMathPolynomials.h"
24#include "GenericPacketMathFrexpLdexp.h"
25#include "GenericPacketMathDoubleWord.h"
26
27namespace Eigen {
28namespace internal {
29
30//----------------------------------------------------------------------
31// Exponential and Logarithmic Functions
32//----------------------------------------------------------------------
33
34// Core range reduction and polynomial evaluation for float logarithm.
35//
36// Given a positive float value v (may be denormal), decomposes it as
37// v = 2^e * (1+f) with f in [sqrt(0.5)-1, sqrt(2)-1], then evaluates
38// log(1+f) ≈ f + f^2 * P(f) using a degree-7 minimax polynomial.
39//
40// Returns the approximation of log(v_mantissa) in log_mantissa and the
41// integer exponent in e. The caller combines these as appropriate
42// (e.g. e*ln2 + log_mantissa for natural log, or log_mantissa*log2e + e
43// for log2).
44//
45// Range reduction uses integer bit manipulation (musl-inspired) instead of the
46// heavier pfrexp_generic, saving ~12 ops. The minimax polynomial was found via
47// Sollya's fpminimax, giving faithfully-rounded results (max 1 ULP for log).
48//
49// Returns whether any lane of v is not a positive, normal, finite value. Such inputs are rare, so packets without
50// them skip the normalization of subnormals here and the special-value handling of the caller.
51template <typename Packet>
52EIGEN_STRONG_INLINE bool plog_core_float(const Packet v, Packet& log_mantissa, Packet& e) {
53 using PacketI = typename unpacket_traits<Packet>::integer_packet;
54
55 const PacketI cst_min_normal = pset1<PacketI>(0x00800000);
56 const PacketI cst_mant_mask = pset1<PacketI>(0x007fffff);
57 // Adding this offset to the integer representation biases the exponent so
58 // that values near 1 (0x3f800000) map to exponent 0, and values below
59 // sqrt(0.5) get folded into the previous exponent. The magic constant is
60 // 0x3f800000 - 0x3f3504f3 = 0x004afb0d, where 0x3f3504f3 ≈ sqrt(0.5).
61 const PacketI cst_sqrt_half_offset = pset1<PacketI>(0x004afb0d);
62 const PacketI cst_exp_bias = pset1<PacketI>(0x7f); // 127
63 const PacketI cst_half_mant = pset1<PacketI>(0x3f3504f3); // sqrt(0.5)
64
65 // The signed comparisons also catch zero and negative values (below the smallest normal), and inf and NaN.
66 PacketI vi = preinterpret<PacketI>(v);
67 const PacketI is_denormal = pcmp_lt(vi, cst_min_normal);
68 const bool any_special = predux_any(preinterpret<Packet>(por(is_denormal, pcmp_lt(pset1<PacketI>(0x7f7fffff), vi))));
69 // Normalize denormals by multiplying by 2^23.
70 if (any_special) {
71 Packet v_normalized = pmul(v, pset1<Packet>(8388608.0f)); // 2^23
72 vi = pselect(is_denormal, preinterpret<PacketI>(v_normalized), vi);
73 }
74
75 // Combined range reduction: bias integer representation so that exponent
76 // extraction automatically shifts mantissa to [sqrt(0.5), sqrt(2)).
77 PacketI vi_biased = padd(vi, cst_sqrt_half_offset);
78 // Extract exponent as integer, subtract bias and denormal adjustment (23).
79 PacketI e_int = psub(plogical_shift_right<23>(vi_biased), cst_exp_bias);
80 if (any_special) e_int = psub(e_int, pand(is_denormal, pset1<PacketI>(23)));
81 e = pcast<PacketI, Packet>(e_int);
82 // Reconstruct mantissa in [sqrt(0.5), sqrt(2)). The integer addition of the
83 // masked mantissa with 0x3f3504f3 (sqrt(0.5)) naturally produces carry into
84 // the exponent field, yielding values in [sqrt(0.5), 1) or [1, sqrt(2)).
85 // Then subtract 1 to center on 0 → f in [sqrt(0.5)-1, sqrt(2)-1].
86 Packet f = psub(preinterpret<Packet>(padd(pand(vi_biased, cst_mant_mask), cst_half_mant)), pset1<Packet>(1.0f));
87
88 // Minimax degree-7 polynomial for g(f) = (log(1+f) - f) / f^2 on
89 // [sqrt(0.5)-1, sqrt(2)-1], so log(1+f) ≈ f + f^2 * P(f).
90 // Generated by Sollya: fpminimax(g, 7, [|single...|], [lo;hi])
91 // Mathematical approximation error: max |log(1+f) - (f + f^2*P(f))| < 2.04e-8.
92 // Coefficients stored in reverse order for ppolevl (highest degree first).
93 constexpr float coeffs[] = {
94 8.8758550584316254e-02f, // c7 (x^7)
95 -1.4199858903884888e-01f, // c6 (x^6)
96 1.4824025332927704e-01f, // c5 (x^5)
97 -1.6583317518234253e-01f, // c4 (x^4)
98 1.9972395896911621e-01f, // c3 (x^3)
99 -2.5001299381256104e-01f, // c2 (x^2)
100 3.3333668112754822e-01f, // c1 (x^1)
101 -4.9999997019767761e-01f, // c0 (x^0)
102 };
103
104 // Evaluate P(f) via Horner's method, then log(1+f) ≈ f + f^2 * P(f).
105 Packet f2 = pmul(f, f);
106 Packet p = ppolevl<Packet, 7>::run(f, coeffs);
107 log_mantissa = pmadd(p, f2, f);
108 return any_special;
109}
110
111// Natural or base-2 logarithm for float packets.
112//
113// Computes log(x) as e*C + log(m), where x = 2^e * m with m in [sqrt(1/2), sqrt(2))
114// and C = ln(2) for natural log, C = 1 for log2.
115template <typename Packet, bool base2>
116EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog_impl_float(const Packet _x) {
117 Packet log_mantissa, e;
118 const bool any_special = plog_core_float(_x, log_mantissa, e);
119
120 // Add the logarithm of the exponent back to the result.
121 Packet x;
122 if (base2) {
123 const Packet cst_log2e = pset1<Packet>(static_cast<float>(EIGEN_LOG2E));
124 x = pmadd(log_mantissa, cst_log2e, e);
125 } else {
126 const Packet cst_ln2 = pset1<Packet>(static_cast<float>(EIGEN_LN2));
127 x = pmadd(e, cst_ln2, log_mantissa);
128 }
129 if (!any_special) return x;
130
131 // Filter out invalid inputs:
132 // - negative arg → NAN
133 // - 0 → -INF
134 // - +INF → +INF
135 const Packet cst_minus_inf = por(psignmask<Packet>(), pinf<Packet>());
136 const Packet cst_pos_inf = pinf<Packet>();
137 Packet invalid_mask = pcmp_lt_or_nan(_x, pzero(_x));
138 Packet iszero_mask = pcmp_eq(_x, pzero(_x));
139 Packet pos_inf_mask = pcmp_eq(_x, cst_pos_inf);
140 return pselect(iszero_mask, cst_minus_inf, por(pselect(pos_inf_mask, cst_pos_inf, x), invalid_mask));
141}
142
143template <typename Packet>
144EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog_float(const Packet _x) {
145 return plog_impl_float<Packet, /* base2 */ false>(_x);
146}
147
148template <typename Packet>
149EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog2_float(const Packet _x) {
150 return plog_impl_float<Packet, /* base2 */ true>(_x);
151}
152
153// -----------------------------------------------------------------------
154// Double logarithm: shared polynomial + two range-reduction backends
155// -----------------------------------------------------------------------
156
157// Cephes rational-polynomial approximation of log(1+f) for
158// f in [sqrt(0.5)-1, sqrt(2)-1].
159// Evaluates x - 0.5*x^2 + x^3 * P(x)/Q(x) where P and Q are degree-5.
160// See: http://www.netlib.org/cephes/
161template <typename Packet>
162EIGEN_STRONG_INLINE Packet plog_mantissa_double(const Packet x) {
163 const Packet cst_cephes_log_p0 = pset1<Packet>(1.01875663804580931796E-4);
164 const Packet cst_cephes_log_p1 = pset1<Packet>(4.97494994976747001425E-1);
165 const Packet cst_cephes_log_p2 = pset1<Packet>(4.70579119878881725854E0);
166 const Packet cst_cephes_log_p3 = pset1<Packet>(1.44989225341610930846E1);
167 const Packet cst_cephes_log_p4 = pset1<Packet>(1.79368678507819816313E1);
168 const Packet cst_cephes_log_p5 = pset1<Packet>(7.70838733755885391666E0);
169 // Q0 = 1.0; pmadd(1, x, q1) simplifies to padd(x, q1).
170 const Packet cst_cephes_log_q1 = pset1<Packet>(1.12873587189167450590E1);
171 const Packet cst_cephes_log_q2 = pset1<Packet>(4.52279145837532221105E1);
172 const Packet cst_cephes_log_q3 = pset1<Packet>(8.29875266912776603211E1);
173 const Packet cst_cephes_log_q4 = pset1<Packet>(7.11544750618563894466E1);
174 const Packet cst_cephes_log_q5 = pset1<Packet>(2.31251620126765340583E1);
175
176 Packet x2 = pmul(x, x);
177 Packet x3 = pmul(x2, x);
178
179 // Evaluate P and Q simultaneously for better ILP.
180 Packet y, y1, y_;
181 y = pmadd(cst_cephes_log_p0, x, cst_cephes_log_p1);
182 y1 = pmadd(cst_cephes_log_p3, x, cst_cephes_log_p4);
183 y = pmadd(y, x, cst_cephes_log_p2);
184 y1 = pmadd(y1, x, cst_cephes_log_p5);
185 y_ = pmadd(y, x3, y1);
186
187 y = padd(x, cst_cephes_log_q1);
188 y1 = pmadd(cst_cephes_log_q3, x, cst_cephes_log_q4);
189 y = pmadd(y, x, cst_cephes_log_q2);
190 y1 = pmadd(y1, x, cst_cephes_log_q5);
191 y = pmadd(y, x3, y1);
192
193 y_ = pmul(y_, x3);
194 y = pdiv(y_, y);
195 y = pnmadd(pset1<Packet>(0.5), x2, y);
196 return padd(x, y);
197}
198
199// Detect whether unpacket_traits<Packet>::integer_packet is defined.
200template <typename Packet, typename = void>
201struct packet_has_integer_packet : std::false_type {};
202template <typename Packet>
203struct packet_has_integer_packet<Packet, void_t<typename unpacket_traits<Packet>::integer_packet>> : std::true_type {};
204
205// Dispatch struct for double-precision range reduction. run() returns whether any lane of v may not be a positive,
206// normal, finite value, as plog_core_float does.
207// Primary template: pfrexp-based fallback (used when integer_packet is absent).
208template <typename Packet, bool UseIntegerPacket>
209struct plog_range_reduce_double {
210 EIGEN_STRONG_INLINE static bool run(const Packet v, Packet& f, Packet& e) {
211 const Packet one = pset1<Packet>(1.0);
212 const Packet cst_cephes_SQRTHF = pset1<Packet>(0.70710678118654752440E0);
213 // pfrexp: f in [0.5, 1), e = unbiased exponent as double.
214 f = pfrexp(v, e);
215 // Shift [0.5,1) -> [sqrt(0.5)-1, sqrt(2)-1] with exponent correction:
216 // if f < sqrt(0.5): f = f + f - 1, e -= 1 (giving f in [0, sqrt(2)-1))
217 // else: f = f - 1 (giving f in [sqrt(0.5)-1, 0))
218 Packet mask = pcmp_lt(f, cst_cephes_SQRTHF);
219 Packet tmp = pand(f, mask);
220 f = psub(f, one);
221 e = psub(e, pand(one, mask));
222 f = padd(f, tmp);
223 return true;
224 }
225};
226
227// Specialisation: fast integer-bit-manipulation path (musl-inspired).
228// Requires unpacket_traits<Packet>::integer_packet to be a 64-bit integer packet.
229template <typename Packet>
230struct plog_range_reduce_double<Packet, true> {
231 EIGEN_STRONG_INLINE static bool run(const Packet v, Packet& f, Packet& e) {
232 using PacketI = typename unpacket_traits<Packet>::integer_packet;
233 // 2^-1022: smallest positive normal double.
234 const PacketI cst_min_normal = pset1<PacketI>(static_cast<int64_t>(0x0010000000000000LL));
235 // Lower 52-bit mask (IEEE mantissa field).
236 const PacketI cst_mant_mask = pset1<PacketI>(static_cast<int64_t>(0x000FFFFFFFFFFFFFLL));
237 // Offset = 1.0_bits - sqrt(0.5)_bits. Adding this to the integer
238 // representation shifts the exponent field so that the [sqrt(0.5), sqrt(2))
239 // half-octave boundary falls on an exact biased-exponent boundary, letting
240 // us extract e with a single right shift. The constant is:
241 // 0x3FF0000000000000 - 0x3FE6A09E667F3BCD = 0x00095F619980C433
242 const PacketI cst_sqrt_half_offset =
243 pset1<PacketI>(static_cast<int64_t>(0x3FF0000000000000LL - 0x3FE6A09E667F3BCDLL));
244 // IEEE double exponent bias (1023).
245 const PacketI cst_exp_bias = pset1<PacketI>(static_cast<int64_t>(1023));
246 // sqrt(0.5) IEEE bits — used to reconstruct f from biased mantissa.
247 const PacketI cst_half_mant = pset1<PacketI>(static_cast<int64_t>(0x3FE6A09E667F3BCDLL));
248
249 // Reinterpret v as a 64-bit integer vector.
250 PacketI vi = preinterpret<PacketI>(v);
251
252 // The signed comparisons also catch zero and negative values (below the smallest normal), and inf and NaN.
253 const PacketI is_denormal = pcmp_lt(vi, cst_min_normal);
254 const bool any_special = predux_any(preinterpret<Packet>(
255 por(is_denormal, pcmp_lt(pset1<PacketI>(static_cast<int64_t>(0x7FEFFFFFFFFFFFFFLL)), vi))));
256 // Normalise denormals: multiply by 2^52 and correct the exponent by -52.
257 if (any_special) {
258 // 2^52 via bit pattern: biased exponent = 52 + 1023 = 0x433, mantissa = 0.
259 Packet v_norm = pmul(v, pset1frombits<Packet>(static_cast<uint64_t>(int64_t(52 + 0x3ff) << 52)));
260 vi = pselect(is_denormal, preinterpret<PacketI>(v_norm), vi);
261 }
262
263 // Bias the integer representation so the exponent field directly encodes
264 // the half-octave index.
265 PacketI vi_biased = padd(vi, cst_sqrt_half_offset);
266 // Extract unbiased exponent: shift out mantissa bits, subtract IEEE bias
267 // and denormal adjustment.
268 PacketI e_int = psub(plogical_shift_right<52>(vi_biased), cst_exp_bias);
269 if (any_special) e_int = psub(e_int, pand(is_denormal, pset1<PacketI>(static_cast<int64_t>(52))));
270 // Convert integer exponent to floating-point.
271 e = pcast<PacketI, Packet>(e_int);
272
273 // Reconstruct mantissa in [sqrt(0.5), sqrt(2)) via integer arithmetic.
274 // The integer addition of the masked mantissa bits and the sqrt(0.5) bit
275 // pattern carries into the exponent field, yielding a value in that range.
276 // Then subtract 1 to centre on 0: f in [sqrt(0.5)-1, sqrt(2)-1].
277 f = psub(preinterpret<Packet>(padd(pand(vi_biased, cst_mant_mask), cst_half_mant)), pset1<Packet>(1.0));
278 return any_special;
279 }
280};
281
282// Core range reduction and polynomial for double logarithm.
283// Input: v > 0 (zero / negative / inf / nan are handled by the caller).
284// Output: log_mantissa ≈ log(mantissa of v in [sqrt(0.5), sqrt(2))),
285// e = unbiased exponent of v as a double.
286// Returns whether the caller must handle special values (see plog_core_float).
287// Selects the fast integer path when integer_packet is available, otherwise
288// falls back to pfrexp.
289template <typename Packet>
290EIGEN_STRONG_INLINE bool plog_core_double(const Packet v, Packet& log_mantissa, Packet& e) {
291 Packet f;
292 const bool any_special = plog_range_reduce_double<Packet, packet_has_integer_packet<Packet>::value>::run(v, f, e);
293 log_mantissa = plog_mantissa_double(f);
294 return any_special;
295}
296
297/* Returns the base e (2.718...) or base 2 logarithm of x.
298 * The argument is separated into its exponent and fractional parts.
299 * The logarithm of the fraction in the interval [sqrt(1/2), sqrt(2)],
300 * is approximated by
301 *
302 * log(1+x) = x - 0.5 x**2 + x**3 P(x)/Q(x).
303 *
304 * for more detail see: http://www.netlib.org/cephes/
305 */
306template <typename Packet, bool base2>
307EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog_impl_double(const Packet _x) {
308 const Packet cst_minus_inf = por(psignmask<Packet>(), pinf<Packet>());
309 const Packet cst_pos_inf = pinf<Packet>();
310
311 Packet log_mantissa, e;
312 const bool any_special = plog_core_double(_x, log_mantissa, e);
313
314 // Combine: log(x) = e * ln2 + log(mantissa), or log2(x) = log(mantissa)*log2e + e.
315 Packet x;
316 if (base2) {
317 const Packet cst_log2e = pset1<Packet>(static_cast<double>(EIGEN_LOG2E));
318 x = pmadd(log_mantissa, cst_log2e, e);
319 } else {
320 const Packet cst_ln2 = pset1<Packet>(static_cast<double>(EIGEN_LN2));
321 x = pmadd(e, cst_ln2, log_mantissa);
322 }
323 if (!any_special) return x;
324
325 Packet invalid_mask = pcmp_lt_or_nan(_x, pzero(_x));
326 Packet iszero_mask = pcmp_eq(_x, pzero(_x));
327 Packet pos_inf_mask = pcmp_eq(_x, cst_pos_inf);
328 // Filter out invalid inputs:
329 // - negative arg → NAN
330 // - 0 → -INF
331 // - +INF → +INF
332 return pselect(iszero_mask, cst_minus_inf, por(pselect(pos_inf_mask, cst_pos_inf, x), invalid_mask));
333}
334
335template <typename Packet>
336EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog_double(const Packet _x) {
337 return plog_impl_double<Packet, /* base2 */ false>(_x);
338}
339
340template <typename Packet>
341EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog2_double(const Packet _x) {
342 return plog_impl_double<Packet, /* base2 */ true>(_x);
343}
344
351template <typename Packet>
352EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_log1p_float(const Packet& x) {
353 const Packet one = pset1<Packet>(1.0f);
354 const Packet cst_minus_inf = por(psignmask<Packet>(), pinf<Packet>());
355 const Packet cst_pos_inf = pinf<Packet>();
356
357 // u = 1 + x, with rounding. Recover the lost low bits: dx = x - (u - 1).
358 Packet u = padd(one, x);
359 pbarrier(u); // -ffast-math would otherwise fold x - (u - 1) to 0.
360 Packet u_minus_one = psub(u, one);
361 pbarrier(u_minus_one); // ... or reassociate it to (x - u) + 1.
362 Packet dx = psub(x, u_minus_one);
363
364 // For |x| tiny enough that u rounds to 1, return x directly.
365 Packet small_mask = pcmp_eq(u, one);
366
367 // Core range reduction and polynomial on u.
368 Packet log_u, e;
369 const bool any_special = plog_core_float(u, log_u, e);
370
371 // result = e * ln2 + log(u) + dx/u.
372 // The dx/u term corrects for the rounding error in u = fl(1+x).
373 const Packet cst_ln2 = pset1<Packet>(static_cast<float>(EIGEN_LN2));
374 Packet result = pmadd(e, cst_ln2, padd(log_u, pdiv(dx, u)));
375 result = pselect(small_mask, x, result);
376 // The remaining cases have u <= 0, u = +inf or u = NaN.
377 if (!any_special) return result;
378
379 // Handle special cases.
380 // For u = +inf (x very large), return +inf.
381 Packet inf_mask = pcmp_eq(u, cst_pos_inf);
382 Packet neg_mask = pcmp_lt(u, pzero(u));
383 Packet zero_mask = pcmp_eq(x, pset1<Packet>(-1.0f));
384 result = pselect(inf_mask, cst_pos_inf, result);
385 result = pselect(zero_mask, cst_minus_inf, result);
386 result = por(neg_mask, result); // NaN for x < -1
387 return result;
388}
389
396template <typename Packet>
397EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_log1p_double(const Packet& x) {
398 const Packet one = pset1<Packet>(1.0);
399 const Packet cst_minus_inf = por(psignmask<Packet>(), pinf<Packet>());
400 const Packet cst_pos_inf = pinf<Packet>();
401
402 // u = 1 + x, with rounding. Recover the lost low bits: dx = x - (u - 1).
403 Packet u = padd(one, x);
404 pbarrier(u); // -ffast-math would otherwise fold x - (u - 1) to 0.
405 Packet u_minus_one = psub(u, one);
406 pbarrier(u_minus_one); // ... or reassociate it to (x - u) + 1.
407 Packet dx = psub(x, u_minus_one);
408
409 // For |x| tiny enough that u rounds to 1, return x directly.
410 Packet small_mask = pcmp_eq(u, one);
411
412 // Core range reduction and polynomial on u.
413 Packet log_u, e;
414 const bool any_special = plog_core_double(u, log_u, e);
415
416 // result = e * ln2 + log(u) + dx/u.
417 // The dx/u term corrects for the rounding error in u = fl(1+x).
418 const Packet cst_ln2 = pset1<Packet>(static_cast<double>(EIGEN_LN2));
419 Packet result = pmadd(e, cst_ln2, padd(log_u, pdiv(dx, u)));
420 result = pselect(small_mask, x, result);
421 // The remaining cases have u <= 0, u = +inf or u = NaN.
422 if (!any_special) return result;
423
424 // Handle special cases.
425 // For u = +inf (x very large), return +inf.
426 Packet inf_mask = pcmp_eq(u, cst_pos_inf);
427 Packet neg_mask = pcmp_lt(u, pzero(u));
428 Packet zero_mask = pcmp_eq(x, pset1<Packet>(-1.0));
429 result = pselect(inf_mask, cst_pos_inf, result);
430 result = pselect(zero_mask, cst_minus_inf, result);
431 result = por(neg_mask, result); // NaN for x < -1
432 return result;
433}
434
439template <typename Packet>
440EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_log1p(const Packet& x) {
441 using ScalarType = typename unpacket_traits<Packet>::type;
442 const Packet one = pset1<Packet>(ScalarType(1));
443 Packet xp1 = padd(x, one);
444 Packet small_mask = pcmp_eq(xp1, one);
445 Packet log1 = plog(xp1);
446 Packet inf_mask = pcmp_eq(xp1, log1);
447 Packet log_large = pmul(x, pdiv(log1, psub(xp1, one)));
448 return pselect(por(small_mask, inf_mask), x, log_large);
449}
450
451// exp(r) for r in [-ln(2)/2, ln(2)/2], by a 6th order minimax polynomial.
452template <typename Packet>
453EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pexp_float_reduced(const Packet& r) {
454 const Packet cst_one = pset1<Packet>(1.0f);
455 const Packet cst_p2 = pset1<Packet>(0.49999988079071044921875f);
456 const Packet cst_p3 = pset1<Packet>(0.16666518151760101318359375f);
457 const Packet cst_p4 = pset1<Packet>(4.166965186595916748046875e-2f);
458 const Packet cst_p5 = pset1<Packet>(8.36894474923610687255859375e-3f);
459 const Packet cst_p6 = pset1<Packet>(1.37449637986719608306884765625e-3f);
460
461 const Packet r2 = pmul(r, r);
462 Packet p_even = pmadd(r2, cst_p6, cst_p4);
463 const Packet p_odd = pmadd(r2, cst_p5, cst_p3);
464 p_even = pmadd(r2, p_even, cst_p2);
465 const Packet p_low = padd(r, cst_one);
466 const Packet y = pmadd(r, p_odd, p_even);
467 return pmadd(r2, y, p_low);
468}
469
470// expm1(r) for r in [-ln(2)/2, ln(2)/2], as r + r^2 P(r). The 5th order polynomial P is Sollya's fpminimax for the
471// relative error of expm1(r), 2^-31; the kernel of pexp_float_reduced, fitted for exp(r), is off by 2^-25 here.
472template <typename Packet>
473EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pexpm1_float_reduced(const Packet& r) {
474 const Packet cst_p2 = pset1<Packet>(0.5f);
475 const Packet cst_p3 = pset1<Packet>(0.1666666567325592041015625f);
476 const Packet cst_p4 = pset1<Packet>(4.16664779186248779296875e-2f);
477 const Packet cst_p5 = pset1<Packet>(8.333566598594188690185546875e-3f);
478 const Packet cst_p6 = pset1<Packet>(1.393371261656284332275390625e-3f);
479 const Packet cst_p7 = pset1<Packet>(1.97434448637068271636962890625e-4f);
480
481 const Packet r2 = pmul(r, r);
482 Packet p_even = pmadd(r2, cst_p6, cst_p4);
483 Packet p_odd = pmadd(r2, cst_p7, cst_p5);
484 p_even = pmadd(r2, p_even, cst_p2);
485 p_odd = pmadd(r2, p_odd, cst_p3);
486 const Packet y = pmadd(r, p_odd, p_even);
487 return pmadd(r2, y, r);
488}
489
490// Exponential function. Works by writing "x = m*log(2) + r" where
491// "m = rint(x/log(2))" and "r" is the remainder. The result is then
492// "exp(x) = 2^m*exp(r)" where exp(r) is in the range [-1,1).
493// exp(r) is computed using a 6th order minimax polynomial approximation.
494template <typename Packet, bool IsFinite>
495EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pexp_float(const Packet _x) {
496 using PacketI = typename unpacket_traits<Packet>::integer_packet;
497
498 const Packet cst_exp_hi = pset1<Packet>(88.723f);
499 const Packet cst_exp_lo = pset1<Packet>(-104.f);
500
501 const Packet cst_cephes_LOG2EF = pset1<Packet>(1.44269504088896341f);
502
503 // Clamp x to prevent overflow/underflow.
504 Packet x = pmin(pmax(_x, cst_exp_lo), cst_exp_hi);
505
506 // Express exp(x) as exp(m*ln(2) + r), start by extracting
507 // m = rint(x/ln(2)).
508 Packet m = print(pmul(x, cst_cephes_LOG2EF));
509
510 // Get r = x - m*ln(2). m*ln(2) is subtracted out in two parts,
511 // m*C1+m*C2 = m*ln(2), to avoid accumulating truncation errors.
512 const Packet cst_cephes_exp_C1 = pset1<Packet>(-0.693359375f);
513 const Packet cst_cephes_exp_C2 = pset1<Packet>(2.12194440e-4f);
514 Packet r = pmadd(m, cst_cephes_exp_C1, x);
515 pbarrier(r); // -ffast-math would otherwise fuse the two products into m (C1 + C2), which rounds.
516 r = pmadd(m, cst_cephes_exp_C2, r);
517
518 Packet y = pexp_float_reduced(r);
519
520 // Construct the result y * 2^m via a 2-way exponent split. Writing
521 // 2^m = 2^floor(m/2) * 2^(m - floor(m/2))
522 // keeps each constructed power-of-two within the normal float range (since
523 // |m| <= 150 after the input clamp implies each half lies in [-75, 65]), so
524 // the IEEE-correct rounding of normal*normal handles the subnormal output
525 // range without special-casing.
526 //
527 // To minimize integer ops we fold the bias into the split:
528 // biased_sum = m + 254 (always nonnegative)
529 // biased_hi = biased_sum >> 1 = m/2 + 127
530 // biased_lo = biased_sum - biased_hi = (m - m/2) + 127
531 // so each <<23 directly yields the float bit pattern for 2^(m/2) and
532 // 2^(m - m/2).
533 const PacketI cst_double_bias = pset1<PacketI>(254);
534 const PacketI mi = pcast<Packet, PacketI>(m);
535 const PacketI biased_sum = padd(mi, cst_double_bias);
536 const PacketI biased_hi = plogical_shift_right<1>(biased_sum); // m/2 + 127
537 const PacketI biased_lo = psub(biased_sum, biased_hi); // (m - m/2) + 127
538 const Packet pow2_hi = preinterpret<Packet>(plogical_shift_left<23>(biased_hi));
539 const Packet pow2_lo = preinterpret<Packet>(plogical_shift_left<23>(biased_lo));
540 // For m = 128, pow2_hi = pow2_lo = 2^64 and y < 1. The barrier keeps -ffast-math from forming 2^64 2^64 = inf.
541 y = pmul(y, pow2_hi);
542 pbarrier(y);
543 y = pmul(y, pow2_lo);
544
545 EIGEN_IF_CONSTEXPR (!IsFinite) {
546 // Handle NaN: exp(nan) = nan. Use pmax to propagate NaN from input.
547 y = pmax(y, _x);
548 }
549 return y;
550}
551
552// exp(g) for g in [-ln(2)/2, ln(2)/2], by the rational interpolant exp(g) = 1 + 2 g P(g^2) / (Q(g^2) - g P(g^2)).
553template <typename Packet>
554EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pexp_double_reduced(const Packet& g) {
555 const Packet cst_1 = pset1<Packet>(1.0);
556 const Packet cst_2 = pset1<Packet>(2.0);
557 const Packet cst_cephes_exp_p0 = pset1<Packet>(1.26177193074810590878e-4);
558 const Packet cst_cephes_exp_p1 = pset1<Packet>(3.02994407707441961300e-2);
559 const Packet cst_cephes_exp_p2 = pset1<Packet>(9.99999999999999999910e-1);
560 const Packet cst_cephes_exp_q0 = pset1<Packet>(3.00198505138664455042e-6);
561 const Packet cst_cephes_exp_q1 = pset1<Packet>(2.52448340349684104192e-3);
562 const Packet cst_cephes_exp_q2 = pset1<Packet>(2.27265548208155028766e-1);
563 const Packet cst_cephes_exp_q3 = pset1<Packet>(2.00000000000000000009e0);
564
565 const Packet x2 = pmul(g, g);
566
567 // Evaluate the numerator polynomial of the rational interpolant.
568 Packet px = cst_cephes_exp_p0;
569 px = pmadd(px, x2, cst_cephes_exp_p1);
570 px = pmadd(px, x2, cst_cephes_exp_p2);
571 px = pmul(px, g);
572
573 // Evaluate the denominator polynomial of the rational interpolant.
574 Packet qx = cst_cephes_exp_q0;
575 qx = pmadd(qx, x2, cst_cephes_exp_q1);
576 qx = pmadd(qx, x2, cst_cephes_exp_q2);
577 qx = pmadd(qx, x2, cst_cephes_exp_q3);
578
579 // exp(g) = 1 + 2*px/(qx - px).
580 return pmadd(cst_2, pdiv(px, psub(qx, px)), cst_1);
581}
582
583// expm1(r) for r in [-ln(2)/2, ln(2)/2], as r + r^2 P(r). The 10th order polynomial P is Sollya's fpminimax for the
584// relative error of expm1(r), 2^-61. The rational interpolant of pexp_double_reduced without its leading 1 would lose
585// up to 5 ulp here, where no 1 hides the rounding errors of its quotient.
586template <typename Packet>
587EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pexpm1_double_reduced(const Packet& r) {
588 const Packet cst_p2 = pset1<Packet>(0.5);
589 const Packet cst_p3 = pset1<Packet>(0.16666666666666677);
590 const Packet cst_p4 = pset1<Packet>(0.04166666666666661);
591 const Packet cst_p5 = pset1<Packet>(0.008333333333321436);
592 const Packet cst_p6 = pset1<Packet>(0.0013888888888923816);
593 const Packet cst_p7 = pset1<Packet>(0.00019841269886601229);
594 const Packet cst_p8 = pset1<Packet>(2.480158723753082e-05);
595 const Packet cst_p9 = pset1<Packet>(2.7557243734579987e-06);
596 const Packet cst_p10 = pset1<Packet>(2.7557352849435147e-07);
597 const Packet cst_p11 = pset1<Packet>(2.510920369520403e-08);
598 const Packet cst_p12 = pset1<Packet>(2.0889530999828774e-09);
599
600 // Even and odd powers in two chains for a shorter dependency chain.
601 const Packet r2 = pmul(r, r);
602 Packet p_even = pmadd(r2, cst_p12, cst_p10);
603 Packet p_odd = pmadd(r2, cst_p11, cst_p9);
604 p_even = pmadd(r2, p_even, cst_p8);
605 p_odd = pmadd(r2, p_odd, cst_p7);
606 p_even = pmadd(r2, p_even, cst_p6);
607 p_odd = pmadd(r2, p_odd, cst_p5);
608 p_even = pmadd(r2, p_even, cst_p4);
609 p_odd = pmadd(r2, p_odd, cst_p3);
610 p_even = pmadd(r2, p_even, cst_p2);
611 const Packet y = pmadd(r, p_odd, p_even);
612 return pmadd(r2, y, r);
613}
614
615template <typename Packet>
616EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pexp_double(const Packet _x) {
617 const Packet cst_exp_hi = pset1<Packet>(709.784);
618 const Packet cst_exp_lo = pset1<Packet>(-745.519);
619 const Packet cst_pldexp_threshold = pset1<Packet>(708.0);
620 const Packet cst_cephes_LOG2EF = pset1<Packet>(1.4426950408889634073599);
621 const Packet cst_cephes_exp_C1 = pset1<Packet>(0.693145751953125);
622 const Packet cst_cephes_exp_C2 = pset1<Packet>(1.42860682030941723212e-6);
623
624 // Clamp x.
625 Packet zero_mask = pcmp_lt(_x, cst_exp_lo);
626 Packet x = pmin(_x, cst_exp_hi);
627
628 // Express exp(x) as exp(g + n*log(2)).
629 // n = rint(x / ln(2)).
630 Packet fx = print(pmul(x, cst_cephes_LOG2EF));
631
632 // Get the remainder modulo log(2), i.e. the "g" described above. Subtract
633 // n*log(2) out in two steps, i.e. n*C1 + n*C2, C1+C2=log2 to get the last
634 // digits right.
635 x = pnmadd(fx, cst_cephes_exp_C1, x);
636 pbarrier(x); // -ffast-math would otherwise fuse the two products into fx (C1 + C2), which rounds.
637 x = pnmadd(fx, cst_cephes_exp_C2, x);
638
639 x = pexp_double_reduced(x);
640
641 // Construct the result 2^n * exp(g) = e * x. The max is used to catch
642 // non-finite values in the input.
643 const Packet fast_pldexp_unsafe = pcmp_lt(cst_pldexp_threshold, pabs(_x));
644 if (!predux_any(fast_pldexp_unsafe)) {
645 // For |x| <= 708, we know the result is not zero or inf, and we can safely use
646 // the fast version of pldexp.
647 return pmax(pldexp_fast(x, fx), _x);
648 }
649 return pandnot(pmax(pldexp(x, fx), _x), zero_mask);
650}
651
652template <typename Packet, typename Scalar = typename unpacket_traits<Packet>::type>
653struct pexp_reduced_impl;
654template <typename Packet>
655struct pexp_reduced_impl<Packet, float> {
656 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& r) { return pexp_float_reduced(r); }
657};
658template <typename Packet>
659struct pexp_reduced_impl<Packet, double> {
660 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& r) { return pexp_double_reduced(r); }
661};
662
663// The reduced-argument kernel of expm1 and the two parts of ln(2) of its Cody-Waite reduction, those of pexp_float and
664// pexp_double.
665template <typename Packet, typename Scalar = typename unpacket_traits<Packet>::type>
666struct pexpm1_reduced_impl;
667template <typename Packet>
668struct pexpm1_reduced_impl<Packet, float> {
669 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& r) { return pexpm1_float_reduced(r); }
670 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float ln2_hi() { return 0.693359375f; }
671 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float ln2_lo() { return -2.12194440e-4f; }
672};
673template <typename Packet>
674struct pexpm1_reduced_impl<Packet, double> {
675 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& r) { return pexpm1_double_reduced(r); }
676 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double ln2_hi() { return 0.693145751953125; }
677 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double ln2_lo() { return 1.42860682030941723212e-6; }
678};
679
685template <typename Packet>
686EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_expm1(const Packet& _x) {
687 using Scalar = typename unpacket_traits<Packet>::type;
688 using Impl = pexpm1_reduced_impl<Packet>;
689 constexpr int max_exponent = std::numeric_limits<Scalar>::max_exponent;
690 constexpr int digits = std::numeric_limits<Scalar>::digits;
691 const Packet one = pset1<Packet>(Scalar(1));
692 // Above max_cap the result is inf, and below min_cap it rounds to -1.
693 const Scalar max_cap = Scalar(max_exponent + 1) * Scalar(EIGEN_LN2);
694 const Scalar min_cap = -Scalar(digits + 2) * Scalar(EIGEN_LN2);
695 const Packet x = pmax(pmin(_x, pset1<Packet>(max_cap)), pset1<Packet>(min_cap));
696
697 const Packet n = print(pmul(x, pset1<Packet>(Scalar(EIGEN_LOG2E))));
698 Packet r = pnmadd(n, pset1<Packet>(Impl::ln2_hi()), x);
699 pbarrier(r); // -ffast-math would otherwise fuse the two products into n (ln2_hi + ln2_lo), which rounds.
700 r = pnmadd(n, pset1<Packet>(Impl::ln2_lo()), r);
701 const Packet em1 = Impl::run(r);
702
703 // c = 1 - 2^-n, exact while it has at most `digits` bits. Beyond that, 2^-n is below half an ulp of 1 for a
704 // positive n, hence the cap, and 1 is below half an ulp of 2^-n for a negative one.
705 // The barrier keeps -ffast-math from forming (em1 + 1) - 2^-n, which cancels em1 for n = 0.
706 Packet c = psub(one, pldexp_fast(one, pnegate(pmin(n, pset1<Packet>(Scalar(digits + 2))))));
707 pbarrier(c);
708 // 2^n (em1 + c) in two steps: 2^n itself overflows for the largest n. The barrier keeps -ffast-math from forming
709 // 2^(n - 1) 2, which overflows for n = max_exponent.
710 Packet y = pldexp_fast(padd(em1, c), psub(n, one));
711 pbarrier(y);
712 y = pmul(y, pset1<Packet>(Scalar(2)));
713 // Below epsilon / 4 in magnitude, x is the result to a quarter of an ulp; returning it keeps the sign of zero and
714 // the subnormals.
715 y = pselect(pcmp_lt(pabs(_x), pset1<Packet>(Scalar(0.25) * NumTraits<Scalar>::epsilon())), _x, y);
716 // A NaN input propagates through the clamp or this max, as in pexp, depending on the NaN convention of pmin and
717 // pmax. expm1(x) >= x, so otherwise the max only replaces a y that rounding left below x, with the closer x.
718 return pmax(y, _x);
719}
720
726template <typename Packet>
727EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_half_exp(const Packet& _x) {
728 using Scalar = typename unpacket_traits<Packet>::type;
729 using Impl = pexpm1_reduced_impl<Packet>;
730 constexpr int max_exponent = std::numeric_limits<Scalar>::max_exponent;
731 // Above max_cap the result is inf.
732 const Scalar max_cap = Scalar(max_exponent + 2) * Scalar(EIGEN_LN2);
733 const Packet x = pmin(_x, pset1<Packet>(max_cap));
734
735 const Packet n = print(pmul(x, pset1<Packet>(Scalar(EIGEN_LOG2E))));
736 Packet r = pnmadd(n, pset1<Packet>(Impl::ln2_hi()), x);
737 pbarrier(r); // -ffast-math would otherwise fuse the two products into n (ln2_hi + ln2_lo), which rounds.
738 r = pnmadd(n, pset1<Packet>(Impl::ln2_lo()), r);
739 // 2^(n - 1) exp(r) in two steps: 2^(n - 1) itself overflows for the largest n. The barrier keeps -ffast-math from
740 // forming 2^(n - 2) 2.
741 Packet y = pldexp_fast(pexp_reduced_impl<Packet>::run(r), psub(n, pset1<Packet>(Scalar(2))));
742 pbarrier(y);
743 y = pmul(y, pset1<Packet>(Scalar(2)));
744 // A NaN input propagates through the clamp or this max, as in pexp, depending on the NaN convention of pmin and
745 // pmax. exp(x) / 2 > x, so otherwise the max changes nothing.
746 return pmax(y, _x);
747}
748
749// 2^f for |f| <= 1/2: f ln(2) = r_hi + r_lo with ln(2) = ln2_hi + ln2_lo, and exp(r) = exp(r_hi) (1 + r_lo) +
750// O(r_lo^2).
751template <typename Packet>
752EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_exp2_reduced(const Packet& f) {
753 using Scalar = typename unpacket_traits<Packet>::type;
754 // ln(2) - ln2_hi, from (double(ln(2)) - ln2_hi) exact in double plus ln(2) - double(ln(2)).
755 const Scalar ln2_hi = Scalar(EIGEN_LN2);
756 const Scalar ln2_lo = Scalar((static_cast<double>(EIGEN_LN2) - double(ln2_hi)) + 2.3190468138462996e-17);
757 Packet r_hi, r_lo;
758 twoprod(pset1<Packet>(ln2_hi), f, r_hi, r_lo);
759 r_lo = pmadd(pset1<Packet>(ln2_lo), f, r_lo);
760 const Packet e = pexp_reduced_impl<Packet>::run(r_hi);
761 return pmadd(e, r_lo, e);
762}
763
764// exp2(x) = 2^n 2^f with n = rint(x) and f = x - n, which is exact with |f| <= 1/2. So exp2(n) = 2^n exactly, and
765// neither the reduction nor the scaling adds an error that grows with |x|.
766template <typename Packet>
767EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet generic_exp2(const Packet& _x) {
768 using Scalar = typename unpacket_traits<Packet>::type;
769 constexpr int max_exponent = std::numeric_limits<Scalar>::max_exponent;
770 constexpr int digits = std::numeric_limits<Scalar>::digits;
771 // Beyond these, the result is inf or rounds to 0; within them, n / 2 and n - n / 2 are normal exponents.
772 constexpr Scalar max_cap = Scalar(max_exponent + 1);
773 constexpr Scalar min_cap = -Scalar(max_exponent + digits - 1);
774 const Packet x = pmax(pmin(_x, pset1<Packet>(max_cap)), pset1<Packet>(min_cap));
775 const Packet n = print(x);
776 const Packet y = generic_exp2_reduced(psub(x, n));
777 // One pldexp_fast while 2^n is normal. Near the ends of the range, y 2^n = (y 2^h) 2^(n - h) with h = rint(n / 2):
778 // both powers are normal and the first product is exact, so only the last one rounds, also into the subnormal range.
779 // The barrier keeps -ffast-math from forming 2^h 2^(n - h), which overflows for n = max_exponent.
780 if (!predux_any(pcmp_lt(pset1<Packet>(Scalar(max_exponent - 2)), pabs(n)))) return pldexp_fast(y, n);
781 const Packet h = print(pmul(n, pset1<Packet>(Scalar(0.5))));
782 Packet out = pldexp_fast(y, h);
783 pbarrier(out);
784 return pldexp_fast(out, psub(n, h));
785}
786
792template <typename Packet>
793EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog10_float(const Packet& x) {
794 // log10(e) in higher precision, split into hi+lo so log_x*(hi+lo) is reconstructed via FMA.
795 // hi = round-to-nearest-float of log10(e); lo = float(log10(e) - hi).
796 const Packet cst_log10e_hi = pset1<Packet>(0.4342944920063018f);
797 const Packet cst_log10e_lo = pset1<Packet>(-1.0103049952192578e-08f);
798 const Packet cst_inf = pinf<Packet>();
799 const Packet cst_zero = pzero(x);
800
801 const Packet log_x = plog(x);
802 const Packet finite_mask = pcmp_lt(pabs(log_x), cst_inf);
803 const Packet finite_log_x = pselect(finite_mask, log_x, cst_zero);
804 const Packet split_log10_x = pmadd(finite_log_x, cst_log10e_hi, pmul(finite_log_x, cst_log10e_lo));
805 return pselect(finite_mask, split_log10_x, log_x);
806}
807
811template <typename Packet>
812EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog10_double(const Packet& x) {
813 const Packet cst_log10e = pset1<Packet>(0.43429448190325182);
814 return pmul(plog(x), cst_log10e);
815}
816
817} // end namespace internal
818} // end namespace Eigen
819
820// Include the split-out sections. Order matters: Pow depends on exp/log and FrexpLdexp,
821// Trig depends on exp (for ptanh_float), Complex depends on Trig (for psincos_selector).
822#include "GenericPacketMathPow.h"
823#include "GenericPacketMathTrig.h"
824#include "GenericPacketMathComplex.h"
825
826namespace Eigen {
827namespace internal {
828
829//----------------------------------------------------------------------
830// Sign Function
831//----------------------------------------------------------------------
832
833template <typename Packet, typename Scalar = typename unpacket_traits<Packet>::type>
834struct psign_uses_binary_encoding
835 : bool_constant<!is_scalar<Packet>::value && packet_has_integer_packet<Packet>::value &&
836 (std::is_same<Scalar, float>::value || std::is_same<Scalar, double>::value)> {};
837
838template <typename Packet>
839struct psign_impl<Packet, std::enable_if_t<psign_uses_binary_encoding<Packet>::value>> {
840 static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) {
841 using Scalar = typename unpacket_traits<Packet>::type;
842 using PacketI = typename unpacket_traits<Packet>::integer_packet;
843 using IntScalar = typename unpacket_traits<PacketI>::type;
844 using Binary = binary_floating_point_traits<Scalar>;
845
846 // Magnitude is a nonnegative integer. Comparing it with 1 avoids Clang
847 // folding an integer == 0 test into a DAZ-sensitive FP comparison.
848 const PacketI magnitude = pand(preinterpret<PacketI>(a), pset1<PacketI>(IntScalar(~Binary::kSignBit)));
849 const Packet is_zero = preinterpret<Packet>(pcmp_lt(magnitude, pset1<PacketI>(IntScalar(1))));
850 const Packet is_nan = preinterpret<Packet>(pcmp_lt(pset1<PacketI>(IntScalar(Binary::kExponentMask)), magnitude));
851 const Packet signed_one = por(pandnot(a, pabs(a)), pset1<Packet>(Scalar(1)));
852 return pselect(is_nan, a, pandnot(signed_one, is_zero));
853 }
854};
855
856template <typename Packet>
857struct psign_impl<Packet, std::enable_if_t<!psign_uses_binary_encoding<Packet>::value && !is_scalar<Packet>::value &&
858 !NumTraits<typename unpacket_traits<Packet>::type>::IsComplex &&
859 !NumTraits<typename unpacket_traits<Packet>::type>::IsInteger>> {
860 static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) {
861 using Scalar = typename unpacket_traits<Packet>::type;
862 const Packet cst_one = pset1<Packet>(Scalar(1));
863
864 const Packet abs_a = pabs(a);
865 const Packet sign_mask = pandnot(a, abs_a);
866 const Packet zero_mask = pcmp_eq(abs_a, pzero(abs_a));
867
868 return pselect(pisnan(a), a, pselect(zero_mask, abs_a, por(sign_mask, cst_one)));
869 }
870};
871
872template <typename Packet>
873struct psign_impl<Packet, std::enable_if_t<!is_scalar<Packet>::value &&
874 !NumTraits<typename unpacket_traits<Packet>::type>::IsComplex &&
875 NumTraits<typename unpacket_traits<Packet>::type>::IsSigned &&
876 NumTraits<typename unpacket_traits<Packet>::type>::IsInteger>> {
877 static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) {
878 using Scalar = typename unpacket_traits<Packet>::type;
879 const Packet cst_one = pset1<Packet>(Scalar(1));
880 const Packet cst_minus_one = pset1<Packet>(Scalar(-1));
881 const Packet cst_zero = pzero(a);
882
883 const Packet positive_mask = pcmp_lt(cst_zero, a);
884 const Packet positive = pand(positive_mask, cst_one);
885 const Packet negative_mask = pcmp_lt(a, cst_zero);
886 const Packet negative = pand(negative_mask, cst_minus_one);
887
888 return por(positive, negative);
889 }
890};
891
892template <typename Packet>
893struct psign_impl<Packet, std::enable_if_t<!is_scalar<Packet>::value &&
894 !NumTraits<typename unpacket_traits<Packet>::type>::IsComplex &&
895 !NumTraits<typename unpacket_traits<Packet>::type>::IsSigned &&
896 NumTraits<typename unpacket_traits<Packet>::type>::IsInteger>> {
897 static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) {
898 using Scalar = typename unpacket_traits<Packet>::type;
899 const Packet cst_one = pset1<Packet>(Scalar(1));
900 const Packet cst_zero = pzero(a);
901
902 const Packet zero_mask = pcmp_eq(cst_zero, a);
903 return pandnot(cst_one, zero_mask);
904 }
905};
906
907// \internal \returns the sign of a complex number z, defined as z / abs(z).
908template <typename Packet>
909struct psign_impl<Packet, std::enable_if_t<!is_scalar<Packet>::value &&
910 NumTraits<typename unpacket_traits<Packet>::type>::IsComplex &&
911 unpacket_traits<Packet>::vectorizable>> {
912 static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) {
913 using Scalar = typename unpacket_traits<Packet>::type;
914 using RealScalar = typename Scalar::value_type;
915 using RealPacket = typename unpacket_traits<Packet>::as_real;
916
917 // Step 1. Compute (for each element z = x + i*y in a)
918 // l = abs(z) = sqrt(x^2 + y^2).
919 // To avoid over- and underflow, we use the stable formula for each hypotenuse
920 // l = (zmin == 0 ? zmax : zmax * sqrt(1 + (zmin/zmax)**2)),
921 // where zmax = max(|x|, |y|), zmin = min(|x|, |y|),
922 RealPacket a_abs = pabs(a.v);
923 RealPacket a_abs_flip = pcplxflip(Packet(a_abs)).v;
924 RealPacket a_max = pmax(a_abs, a_abs_flip);
925 RealPacket a_min = pmin(a_abs, a_abs_flip);
926 RealPacket a_min_zero_mask = pcmp_eq(a_min, pzero(a_min));
927 RealPacket a_max_zero_mask = pcmp_eq(a_max, pzero(a_max));
928 RealPacket r = pdiv(a_min, a_max);
929 const RealPacket cst_one = pset1<RealPacket>(RealScalar(1));
930 RealPacket l = pmul(a_max, psqrt(pmadd(r, r, cst_one))); // [l0, l0, l1, l1]
931 // Set l to a_max if a_min is zero, since the roundtrip sqrt(a_max^2) may be
932 // lossy.
933 l = pselect(a_min_zero_mask, a_max, l);
934 // Step 2 compute a / abs(a).
935 RealPacket sign_as_real = pandnot(pdiv(a.v, l), a_max_zero_mask);
936 // l overflows only for a_max > highest / sqrt(2), and is inexact for subnormal a_max. Elements with a_max < min or
937 // a_max > highest / 2, as in the scalar sign_impl, are recomputed as (a / a_max) / sqrt(1 + r^2), whose first
938 // factor has max(|Re|, |Im|) = 1; the others keep a / l. A NaN component gives NaN in both, as the scalar version
939 // does. Non-finite a_max keeps a / l.
940 const RealPacket cst_min = pset1<RealPacket>((numext::numeric_limits<RealScalar>::min)());
941 const RealPacket cst_highest = pset1<RealPacket>(NumTraits<RealScalar>::highest());
942 const RealPacket cst_half_highest = pset1<RealPacket>(NumTraits<RealScalar>::highest() / RealScalar(2));
943 const RealPacket extreme = por(pandnot(pcmp_lt(a_max, cst_min), a_max_zero_mask), pcmp_lt(cst_half_highest, a_max));
944 if (EIGEN_PREDICT_FALSE(predux_any(extreme))) {
945 RealPacket unit_sign = pdiv(pdiv(a.v, a_max), psqrt(pmadd(r, r, cst_one)));
946 const RealPacket a_nan = pisnan(a.v);
947 const RealPacket any_nan = por(a_nan, pcplxflip(Packet(a_nan)).v);
948 unit_sign = pselect(any_nan, padd(a.v, pcplxflip(a).v), unit_sign);
949 sign_as_real = pselect(pand(extreme, pcmp_le(a_max, cst_highest)), unit_sign, sign_as_real);
950 }
951 Packet sign;
952 sign.v = sign_as_real;
953 return sign;
954 }
955};
956
957//----------------------------------------------------------------------
958// Rounding Functions
959//----------------------------------------------------------------------
960
961template <typename Packet>
962EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet generic_rint(const Packet& a) {
963 using Scalar = typename unpacket_traits<Packet>::type;
964 using IntType = typename numext::get_integer_by_size<sizeof(Scalar)>::signed_type;
965 // Adds and subtracts signum(a) * 2^kMantissaBits to force rounding.
966 const IntType kLimit = IntType(1) << (NumTraits<Scalar>::digits() - 1);
967 const Packet cst_limit = pset1<Packet>(static_cast<Scalar>(kLimit));
968 Packet abs_a = pabs(a);
969 Packet sign_a = pandnot(a, abs_a);
970 Packet rint_a = padd(abs_a, cst_limit);
971 // Don't compile-away addition and subtraction.
972 pbarrier(rint_a);
973 rint_a = psub(rint_a, cst_limit);
974 rint_a = por(rint_a, sign_a);
975 // If greater than limit (or NaN), simply return a.
976 Packet mask = pcmp_lt(abs_a, cst_limit);
977 Packet result = pselect(mask, rint_a, a);
978 return result;
979}
980
981template <typename Packet>
982EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet generic_floor(const Packet& a) {
983 using Scalar = typename unpacket_traits<Packet>::type;
984 const Packet cst_1 = pset1<Packet>(Scalar(1));
985 Packet rint_a = generic_rint(a);
986 // if a < rint(a), then rint(a) == ceil(a)
987 Packet mask = pcmp_lt(a, rint_a);
988 Packet offset = pand(cst_1, mask);
989 Packet result = psub(rint_a, offset);
990 return result;
991}
992
993template <typename Packet>
994EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet generic_ceil(const Packet& a) {
995 using Scalar = typename unpacket_traits<Packet>::type;
996 const Packet cst_1 = pset1<Packet>(Scalar(1));
997 const Packet sign_mask = psignmask<Packet>();
998 Packet rint_a = generic_rint(a);
999 // if rint(a) < a, then rint(a) == floor(a)
1000 Packet mask = pcmp_lt(rint_a, a);
1001 Packet offset = pand(cst_1, mask);
1002 Packet result = padd(rint_a, offset);
1003 // Signed zero must remain signed (e.g. ceil(-0.02) == -0).
1004 result = por(result, pand(sign_mask, a));
1005 return result;
1006}
1007
1008template <typename Packet>
1009EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet generic_trunc(const Packet& a) {
1010 Packet abs_a = pabs(a);
1011 Packet sign_a = pandnot(a, abs_a);
1012 Packet floor_abs_a = generic_floor(abs_a);
1013 Packet result = por(floor_abs_a, sign_a);
1014 return result;
1015}
1016
1017template <typename Packet>
1018EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet generic_round(const Packet& a) {
1019 using Scalar = typename unpacket_traits<Packet>::type;
1020 const Packet cst_half = pset1<Packet>(Scalar(0.5));
1021 const Packet cst_1 = pset1<Packet>(Scalar(1));
1022 Packet abs_a = pabs(a);
1023 Packet sign_a = pandnot(a, abs_a);
1024 Packet floor_abs_a = generic_floor(abs_a);
1025 Packet diff = psub(abs_a, floor_abs_a);
1026 Packet mask = pcmp_le(cst_half, diff);
1027 Packet offset = pand(cst_1, mask);
1028 Packet result = padd(floor_abs_a, offset);
1029 result = por(result, sign_a);
1030 return result;
1031}
1032
1033template <typename Packet>
1034struct nearest_integer_packetop_impl<Packet, /*IsScalar*/ false, /*IsInteger*/ false> {
1035 using Scalar = typename unpacket_traits<Packet>::type;
1036 static_assert(packet_traits<Scalar>::HasRound, "Generic nearest integer functions are disabled for this type.");
1037 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_floor(const Packet& x) { return generic_floor(x); }
1038 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_ceil(const Packet& x) { return generic_ceil(x); }
1039 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_rint(const Packet& x) { return generic_rint(x); }
1040 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_round(const Packet& x) { return generic_round(x); }
1041 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_trunc(const Packet& x) { return generic_trunc(x); }
1042};
1043
1044template <typename Packet>
1045struct nearest_integer_packetop_impl<Packet, /*IsScalar*/ false, /*IsInteger*/ true> {
1046 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_floor(const Packet& x) { return x; }
1047 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_ceil(const Packet& x) { return x; }
1048 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_rint(const Packet& x) { return x; }
1049 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_round(const Packet& x) { return x; }
1050 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_trunc(const Packet& x) { return x; }
1051};
1052
1053} // end namespace internal
1054} // end namespace Eigen
1055
1056#endif // EIGEN_ARCH_GENERIC_PACKET_MATH_FUNCTIONS_H