1/* origin: OpenBSD /usr/src/lib/libm/src/ld80/e_powl.c */
  2/*
  3 * Copyright (c) 2008 Stephen L. Moshier <steve@moshier.net>
  4 *
  5 * Permission to use, copy, modify, and distribute this software for any
  6 * purpose with or without fee is hereby granted, provided that the above
  7 * copyright notice and this permission notice appear in all copies.
  8 *
  9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 16 */
 17/*                                                      powl.c
 18 *
 19 *      Power function, long double precision
 20 *
 21 *
 22 * SYNOPSIS:
 23 *
 24 * long double x, y, z, powl();
 25 *
 26 * z = powl( x, y );
 27 *
 28 *
 29 * DESCRIPTION:
 30 *
 31 * Computes x raised to the yth power.  Analytically,
 32 *
 33 *      x**y  =  exp( y log(x) ).
 34 *
 35 * Following Cody and Waite, this program uses a lookup table
 36 * of 2**-i/32 and pseudo extended precision arithmetic to
 37 * obtain several extra bits of accuracy in both the logarithm
 38 * and the exponential.
 39 *
 40 *
 41 * ACCURACY:
 42 *
 43 * The relative error of pow(x,y) can be estimated
 44 * by   y dl ln(2),   where dl is the absolute error of
 45 * the internally computed base 2 logarithm.  At the ends
 46 * of the approximation interval the logarithm equal 1/32
 47 * and its relative error is about 1 lsb = 1.1e-19.  Hence
 48 * the predicted relative error in the result is 2.3e-21 y .
 49 *
 50 *                      Relative error:
 51 * arithmetic   domain     # trials      peak         rms
 52 *
 53 *    IEEE     +-1000       40000      2.8e-18      3.7e-19
 54 * .001 < x < 1000, with log(x) uniformly distributed.
 55 * -1000 < y < 1000, y uniformly distributed.
 56 *
 57 *    IEEE     0,8700       60000      6.5e-18      1.0e-18
 58 * 0.99 < x < 1.01, 0 < y < 8700, uniformly distributed.
 59 *
 60 *
 61 * ERROR MESSAGES:
 62 *
 63 *   message         condition      value returned
 64 * pow overflow     x**y > MAXNUM      INFINITY
 65 * pow underflow   x**y < 1/MAXNUM       0.0
 66 * pow domain      x<0 and y noninteger  0.0
 67 *
 68 */
 69
 70#include "libm.h"
 71
 72#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
 73long double powl(long double x, long double y)
 74{
 75	return pow(x, y);
 76}
 77#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384
 78
 79/* Table size */
 80#define NXT 32
 81
 82/* log(1+x) =  x - .5x^2 + x^3 *  P(z)/Q(z)
 83 * on the domain  2^(-1/32) - 1  <=  x  <=  2^(1/32) - 1
 84 */
 85static const long double P[] = {
 86 8.3319510773868690346226E-4L,
 87 4.9000050881978028599627E-1L,
 88 1.7500123722550302671919E0L,
 89 1.4000100839971580279335E0L,
 90};
 91static const long double Q[] = {
 92/* 1.0000000000000000000000E0L,*/
 93 5.2500282295834889175431E0L,
 94 8.4000598057587009834666E0L,
 95 4.2000302519914740834728E0L,
 96};
 97/* A[i] = 2^(-i/32), rounded to IEEE long double precision.
 98 * If i is even, A[i] + B[i/2] gives additional accuracy.
 99 */
100static const long double A[33] = {
101 1.0000000000000000000000E0L,
102 9.7857206208770013448287E-1L,
103 9.5760328069857364691013E-1L,
104 9.3708381705514995065011E-1L,
105 9.1700404320467123175367E-1L,
106 8.9735453750155359320742E-1L,
107 8.7812608018664974155474E-1L,
108 8.5930964906123895780165E-1L,
109 8.4089641525371454301892E-1L,
110 8.2287773907698242225554E-1L,
111 8.0524516597462715409607E-1L,
112 7.8799042255394324325455E-1L,
113 7.7110541270397041179298E-1L,
114 7.5458221379671136985669E-1L,
115 7.3841307296974965571198E-1L,
116 7.2259040348852331001267E-1L,
117 7.0710678118654752438189E-1L,
118 6.9195494098191597746178E-1L,
119 6.7712777346844636413344E-1L,
120 6.6261832157987064729696E-1L,
121 6.4841977732550483296079E-1L,
122 6.3452547859586661129850E-1L,
123 6.2092890603674202431705E-1L,
124 6.0762367999023443907803E-1L,
125 5.9460355750136053334378E-1L,
126 5.8186242938878875689693E-1L,
127 5.6939431737834582684856E-1L,
128 5.5719337129794626814472E-1L,
129 5.4525386633262882960438E-1L,
130 5.3357020033841180906486E-1L,
131 5.2213689121370692017331E-1L,
132 5.1094857432705833910408E-1L,
133 5.0000000000000000000000E-1L,
134};
135static const long double B[17] = {
136 0.0000000000000000000000E0L,
137 2.6176170809902549338711E-20L,
138-1.0126791927256478897086E-20L,
139 1.3438228172316276937655E-21L,
140 1.2207982955417546912101E-20L,
141-6.3084814358060867200133E-21L,
142 1.3164426894366316434230E-20L,
143-1.8527916071632873716786E-20L,
144 1.8950325588932570796551E-20L,
145 1.5564775779538780478155E-20L,
146 6.0859793637556860974380E-21L,
147-2.0208749253662532228949E-20L,
148 1.4966292219224761844552E-20L,
149 3.3540909728056476875639E-21L,
150-8.6987564101742849540743E-22L,
151-1.2327176863327626135542E-20L,
152 0.0000000000000000000000E0L,
153};
154
155/* 2^x = 1 + x P(x),
156 * on the interval -1/32 <= x <= 0
157 */
158static const long double R[] = {
159 1.5089970579127659901157E-5L,
160 1.5402715328927013076125E-4L,
161 1.3333556028915671091390E-3L,
162 9.6181291046036762031786E-3L,
163 5.5504108664798463044015E-2L,
164 2.4022650695910062854352E-1L,
165 6.9314718055994530931447E-1L,
166};
167
168#define MEXP (NXT*16384.0L)
169/* The following if denormal numbers are supported, else -MEXP: */
170#define MNEXP (-NXT*(16384.0L+64.0L))
171/* log2(e) - 1 */
172#define LOG2EA 0.44269504088896340735992L
173
174#define F W
175#define Fa Wa
176#define Fb Wb
177#define G W
178#define Ga Wa
179#define Gb u
180#define H W
181#define Ha Wb
182#define Hb Wb
183
184static const long double MAXLOGL = 1.1356523406294143949492E4L;
185static const long double MINLOGL = -1.13994985314888605586758E4L;
186static const long double LOGE2L = 6.9314718055994530941723E-1L;
187static const long double huge = 0x1p10000L;
188/* XXX Prevent gcc from erroneously constant folding this. */
189#ifdef __wasilibc_unmodified_upstream // WASI doesn't need old GCC workarounds
190static const volatile long double twom10000 = 0x1p-10000L;
191#else
192static const long double twom10000 = 0x1p-10000L;
193#endif
194
195static long double reducl(long double);
196static long double powil(long double, int);
197
198long double powl(long double x, long double y)
199{
200	/* double F, Fa, Fb, G, Ga, Gb, H, Ha, Hb */
201	int i, nflg, iyflg, yoddint;
202	long e;
203	volatile long double z=0;
204	long double w=0, W=0, Wa=0, Wb=0, ya=0, yb=0, u=0;
205
206	/* make sure no invalid exception is raised by nan comparision */
207	if (isnan(x)) {
208		if (!isnan(y) && y == 0.0)
209			return 1.0;
210		return x;
211	}
212	if (isnan(y)) {
213		if (x == 1.0)
214			return 1.0;
215		return y;
216	}
217	if (x == 1.0)
218		return 1.0; /* 1**y = 1, even if y is nan */
219	if (y == 0.0)
220		return 1.0; /* x**0 = 1, even if x is nan */
221	if (y == 1.0)
222		return x;
223	/* if y*log2(x) < log2(LDBL_TRUE_MIN)-1 then x^y uflows to 0
224	   if y*log2(x) > -log2(LDBL_TRUE_MIN)+1 > LDBL_MAX_EXP then x^y oflows
225	   if |x|!=1 then |log2(x)| > |log(x)| > LDBL_EPSILON/2 so
226	   x^y oflows/uflows if |y|*LDBL_EPSILON/2 > -log2(LDBL_TRUE_MIN)+1 */
227	if (fabsl(y) > 2*(-LDBL_MIN_EXP+LDBL_MANT_DIG+1)/LDBL_EPSILON) {
228		/* y is not an odd int */
229		if (x == -1.0)
230			return 1.0;
231		if (y == INFINITY) {
232			if (x > 1.0 || x < -1.0)
233				return INFINITY;
234			return 0.0;
235		}
236		if (y == -INFINITY) {
237			if (x > 1.0 || x < -1.0)
238				return 0.0;
239			return INFINITY;
240		}
241		if ((x > 1.0 || x < -1.0) == (y > 0))
242			return huge * huge;
243		return twom10000 * twom10000;
244	}
245	if (x == INFINITY) {
246		if (y > 0.0)
247			return INFINITY;
248		return 0.0;
249	}
250
251	w = floorl(y);
252
253	/* Set iyflg to 1 if y is an integer. */
254	iyflg = 0;
255	if (w == y)
256		iyflg = 1;
257
258	/* Test for odd integer y. */
259	yoddint = 0;
260	if (iyflg) {
261		ya = fabsl(y);
262		ya = floorl(0.5 * ya);
263		yb = 0.5 * fabsl(w);
264		if( ya != yb )
265			yoddint = 1;
266	}
267
268	if (x == -INFINITY) {
269		if (y > 0.0) {
270			if (yoddint)
271				return -INFINITY;
272			return INFINITY;
273		}
274		if (y < 0.0) {
275			if (yoddint)
276				return -0.0;
277			return 0.0;
278		}
279	}
280	nflg = 0; /* (x<0)**(odd int) */
281	if (x <= 0.0) {
282		if (x == 0.0) {
283			if (y < 0.0) {
284				if (signbit(x) && yoddint)
285					/* (-0.0)**(-odd int) = -inf, divbyzero */
286					return -1.0/0.0;
287				/* (+-0.0)**(negative) = inf, divbyzero */
288				return 1.0/0.0;
289			}
290			if (signbit(x) && yoddint)
291				return -0.0;
292			return 0.0;
293		}
294		if (iyflg == 0)
295			return (x - x) / (x - x); /* (x<0)**(non-int) is NaN */
296		/* (x<0)**(integer) */
297		if (yoddint)
298			nflg = 1; /* negate result */
299		x = -x;
300	}
301	/* (+integer)**(integer)  */
302	if (iyflg && floorl(x) == x && fabsl(y) < 32768.0) {
303		w = powil(x, (int)y);
304		return nflg ? -w : w;
305	}
306
307	/* separate significand from exponent */
308	x = frexpl(x, &i);
309	e = i;
310
311	/* find significand in antilog table A[] */
312	i = 1;
313	if (x <= A[17])
314		i = 17;
315	if (x <= A[i+8])
316		i += 8;
317	if (x <= A[i+4])
318		i += 4;
319	if (x <= A[i+2])
320		i += 2;
321	if (x >= A[1])
322		i = -1;
323	i += 1;
324
325	/* Find (x - A[i])/A[i]
326	 * in order to compute log(x/A[i]):
327	 *
328	 * log(x) = log( a x/a ) = log(a) + log(x/a)
329	 *
330	 * log(x/a) = log(1+v),  v = x/a - 1 = (x-a)/a
331	 */
332	x -= A[i];
333	x -= B[i/2];
334	x /= A[i];
335
336	/* rational approximation for log(1+v):
337	 *
338	 * log(1+v)  =  v  -  v**2/2  +  v**3 P(v) / Q(v)
339	 */
340	z = x*x;
341	w = x * (z * __polevll(x, P, 3) / __p1evll(x, Q, 3));
342	w = w - 0.5*z;
343
344	/* Convert to base 2 logarithm:
345	 * multiply by log2(e) = 1 + LOG2EA
346	 */
347	z = LOG2EA * w;
348	z += w;
349	z += LOG2EA * x;
350	z += x;
351
352	/* Compute exponent term of the base 2 logarithm. */
353	w = -i;
354	w /= NXT;
355	w += e;
356	/* Now base 2 log of x is w + z. */
357
358	/* Multiply base 2 log by y, in extended precision. */
359
360	/* separate y into large part ya
361	 * and small part yb less than 1/NXT
362	 */
363	ya = reducl(y);
364	yb = y - ya;
365
366	/* (w+z)(ya+yb)
367	 * = w*ya + w*yb + z*y
368	 */
369	F = z * y  +  w * yb;
370	Fa = reducl(F);
371	Fb = F - Fa;
372
373	G = Fa + w * ya;
374	Ga = reducl(G);
375	Gb = G - Ga;
376
377	H = Fb + Gb;
378	Ha = reducl(H);
379	w = (Ga + Ha) * NXT;
380
381	/* Test the power of 2 for overflow */
382	if (w > MEXP)
383		return huge * huge;  /* overflow */
384	if (w < MNEXP)
385		return twom10000 * twom10000;  /* underflow */
386
387	e = w;
388	Hb = H - Ha;
389
390	if (Hb > 0.0) {
391		e += 1;
392		Hb -= 1.0/NXT;  /*0.0625L;*/
393	}
394
395	/* Now the product y * log2(x)  =  Hb + e/NXT.
396	 *
397	 * Compute base 2 exponential of Hb,
398	 * where -0.0625 <= Hb <= 0.
399	 */
400	z = Hb * __polevll(Hb, R, 6);  /*  z = 2**Hb - 1  */
401
402	/* Express e/NXT as an integer plus a negative number of (1/NXT)ths.
403	 * Find lookup table entry for the fractional power of 2.
404	 */
405	if (e < 0)
406		i = 0;
407	else
408		i = 1;
409	i = e/NXT + i;
410	e = NXT*i - e;
411	w = A[e];
412	z = w * z;  /*  2**-e * ( 1 + (2**Hb-1) )  */
413	z = z + w;
414	z = scalbnl(z, i);  /* multiply by integer power of 2 */
415
416	if (nflg)
417		z = -z;
418	return z;
419}
420
421
422/* Find a multiple of 1/NXT that is within 1/NXT of x. */
423static long double reducl(long double x)
424{
425	long double t;
426
427	t = x * NXT;
428	t = floorl(t);
429	t = t / NXT;
430	return t;
431}
432
433/*
434 *      Positive real raised to integer power, long double precision
435 *
436 *
437 * SYNOPSIS:
438 *
439 * long double x, y, powil();
440 * int n;
441 *
442 * y = powil( x, n );
443 *
444 *
445 * DESCRIPTION:
446 *
447 * Returns argument x>0 raised to the nth power.
448 * The routine efficiently decomposes n as a sum of powers of
449 * two. The desired power is a product of two-to-the-kth
450 * powers of x.  Thus to compute the 32767 power of x requires
451 * 28 multiplications instead of 32767 multiplications.
452 *
453 *
454 * ACCURACY:
455 *
456 *                      Relative error:
457 * arithmetic   x domain   n domain  # trials      peak         rms
458 *    IEEE     .001,1000  -1022,1023  50000       4.3e-17     7.8e-18
459 *    IEEE        1,2     -1022,1023  20000       3.9e-17     7.6e-18
460 *    IEEE     .99,1.01     0,8700    10000       3.6e-16     7.2e-17
461 *
462 * Returns MAXNUM on overflow, zero on underflow.
463 */
464
465static long double powil(long double x, int nn)
466{
467	long double ww, y;
468	long double s;
469	int n, e, sign, lx;
470
471	if (nn == 0)
472		return 1.0;
473
474	if (nn < 0) {
475		sign = -1;
476		n = -nn;
477	} else {
478		sign = 1;
479		n = nn;
480	}
481
482	/* Overflow detection */
483
484	/* Calculate approximate logarithm of answer */
485	s = x;
486	s = frexpl( s, &lx);
487	e = (lx - 1)*n;
488	if ((e == 0) || (e > 64) || (e < -64)) {
489		s = (s - 7.0710678118654752e-1L) / (s +  7.0710678118654752e-1L);
490		s = (2.9142135623730950L * s - 0.5 + lx) * nn * LOGE2L;
491	} else {
492		s = LOGE2L * e;
493	}
494
495	if (s > MAXLOGL)
496		return huge * huge;  /* overflow */
497
498	if (s < MINLOGL)
499		return twom10000 * twom10000;  /* underflow */
500	/* Handle tiny denormal answer, but with less accuracy
501	 * since roundoff error in 1.0/x will be amplified.
502	 * The precise demarcation should be the gradual underflow threshold.
503	 */
504	if (s < -MAXLOGL+2.0) {
505		x = 1.0/x;
506		sign = -sign;
507	}
508
509	/* First bit of the power */
510	if (n & 1)
511		y = x;
512	else
513		y = 1.0;
514
515	ww = x;
516	n >>= 1;
517	while (n) {
518		ww = ww * ww;   /* arg to the 2-to-the-kth power */
519		if (n & 1)     /* if that bit is set, then include in product */
520			y *= ww;
521		n >>= 1;
522	}
523
524	if (sign < 0)
525		y = 1.0/y;
526	return y;
527}
528#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384
529// TODO: broken implementation to make things compile
530long double powl(long double x, long double y)
531{
532	return pow(x, y);
533}
534#endif