xref: /original-bsd/lib/libm/ieee/cbrt.c (revision e811aa08)
1 /*
2  * Copyright (c) 1985, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)cbrt.c	8.1 (Berkeley) 06/04/93";
10 #endif /* not lint */
11 
12 #include <sys/cdefs.h>
13 
14 /* kahan's cube root (53 bits IEEE double precision)
15  * for IEEE machines only
16  * coded in C by K.C. Ng, 4/30/85
17  *
18  * Accuracy:
19  *	better than 0.667 ulps according to an error analysis. Maximum
20  * error observed was 0.666 ulps in an 1,000,000 random arguments test.
21  *
22  * Warning: this code is semi machine dependent; the ordering of words in
23  * a floating point number must be known in advance. I assume that the
24  * long interger at the address of a floating point number will be the
25  * leading 32 bits of that floating point number (i.e., sign, exponent,
26  * and the 20 most significant bits).
27  * On a National machine, it has different ordering; therefore, this code
28  * must be compiled with flag -DNATIONAL.
29  */
30 #if !defined(vax)&&!defined(tahoe)
31 
32 static const unsigned long
33 		     B1 = 715094163, /* B1 = (682-0.03306235651)*2**20 */
34 	             B2 = 696219795; /* B2 = (664-0.03306235651)*2**20 */
35 static const double
36 	    C= 19./35.,
37 	    D= -864./1225.,
38 	    E= 99./70.,
39 	    F= 45./28.,
40 	    G= 5./14.;
41 
42 double cbrt(x)
43 double x;
44 {
45 	double r,s,t=0.0,w;
46 	unsigned long *px = (unsigned long *) &x,
47 	              *pt = (unsigned long *) &t,
48 		      mexp,sign;
49 
50 #ifdef national /* ordering of words in a floating points number */
51 	const int n0=1,n1=0;
52 #else	/* national */
53 	const int n0=0,n1=1;
54 #endif	/* national */
55 
56 	mexp=px[n0]&0x7ff00000;
57 	if(mexp==0x7ff00000) return(x); /* cbrt(NaN,INF) is itself */
58 	if(x==0.0) return(x);		/* cbrt(0) is itself */
59 
60 	sign=px[n0]&0x80000000; /* sign= sign(x) */
61 	px[n0] ^= sign;		/* x=|x| */
62 
63 
64     /* rough cbrt to 5 bits */
65 	if(mexp==0) 		/* subnormal number */
66 	  {pt[n0]=0x43500000; 	/* set t= 2**54 */
67 	   t*=x; pt[n0]=pt[n0]/3+B2;
68 	  }
69 	else
70 	  pt[n0]=px[n0]/3+B1;
71 
72 
73     /* new cbrt to 23 bits, may be implemented in single precision */
74 	r=t*t/x;
75 	s=C+r*t;
76 	t*=G+F/(s+E+D/s);
77 
78     /* chopped to 20 bits and make it larger than cbrt(x) */
79 	pt[n1]=0; pt[n0]+=0x00000001;
80 
81 
82     /* one step newton iteration to 53 bits with error less than 0.667 ulps */
83 	s=t*t;		/* t*t is exact */
84 	r=x/s;
85 	w=t+t;
86 	r=(r-t)/(w+r);	/* r-t is exact */
87 	t=t+t*r;
88 
89 
90     /* retore the sign bit */
91 	pt[n0] |= sign;
92 	return(t);
93 }
94 #endif
95