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