cbrtf.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /* cbrtf.c
  2. *
  3. * Cube root
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * float x, y, cbrtf();
  10. *
  11. * y = cbrtf( x );
  12. *
  13. *
  14. *
  15. * DESCRIPTION:
  16. *
  17. * Returns the cube root of the argument, which may be negative.
  18. *
  19. * Range reduction involves determining the power of 2 of
  20. * the argument. A polynomial of degree 2 applied to the
  21. * mantissa, and multiplication by the cube root of 1, 2, or 4
  22. * approximates the root to within about 0.1%. Then Newton's
  23. * iteration is used to converge to an accurate result.
  24. *
  25. *
  26. *
  27. * ACCURACY:
  28. *
  29. * Relative error:
  30. * arithmetic domain # trials peak rms
  31. * IEEE 0,1e38 100000 7.6e-8 2.7e-8
  32. *
  33. */
  34. /* cbrt.c */
  35. /*
  36. Cephes Math Library Release 2.2: June, 1992
  37. Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier
  38. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  39. */
  40. #include <math.h>
  41. static float CBRT2 = 1.25992104989487316477;
  42. static float CBRT4 = 1.58740105196819947475;
  43. float frexpf(float, int *), ldexpf(float, int);
  44. float cbrtf( float xx )
  45. {
  46. int e, rem, sign;
  47. float x, z;
  48. x = xx;
  49. if( x == 0 )
  50. return( 0.0 );
  51. if( x > 0 )
  52. sign = 1;
  53. else
  54. {
  55. sign = -1;
  56. x = -x;
  57. }
  58. z = x;
  59. /* extract power of 2, leaving
  60. * mantissa between 0.5 and 1
  61. */
  62. x = frexpf( x, &e );
  63. /* Approximate cube root of number between .5 and 1,
  64. * peak relative error = 9.2e-6
  65. */
  66. x = (((-0.13466110473359520655053 * x
  67. + 0.54664601366395524503440 ) * x
  68. - 0.95438224771509446525043 ) * x
  69. + 1.1399983354717293273738 ) * x
  70. + 0.40238979564544752126924;
  71. /* exponent divided by 3 */
  72. if( e >= 0 )
  73. {
  74. rem = e;
  75. e /= 3;
  76. rem -= 3*e;
  77. if( rem == 1 )
  78. x *= CBRT2;
  79. else if( rem == 2 )
  80. x *= CBRT4;
  81. }
  82. /* argument less than 1 */
  83. else
  84. {
  85. e = -e;
  86. rem = e;
  87. e /= 3;
  88. rem -= 3*e;
  89. if( rem == 1 )
  90. x /= CBRT2;
  91. else if( rem == 2 )
  92. x /= CBRT4;
  93. e = -e;
  94. }
  95. /* multiply by power of 2 */
  96. x = ldexpf( x, e );
  97. /* Newton iteration */
  98. x -= ( x - (z/(x*x)) ) * 0.333333333333;
  99. if( sign < 0 )
  100. x = -x;
  101. return(x);
  102. }