tanhf.c 580 B

1234567891011121314151617181920212223242526272829303132333435
  1. #include "libm.h"
  2. float tanhf(float x)
  3. {
  4. union {float f; uint32_t i;} u = {.f = x};
  5. uint32_t w;
  6. int sign;
  7. float t;
  8. /* x = |x| */
  9. sign = u.i >> 31;
  10. u.i &= 0x7fffffff;
  11. x = u.f;
  12. w = u.i;
  13. if (w > 0x3f0c9f54) {
  14. /* |x| > log(3)/2 ~= 0.5493 or nan */
  15. if (w > 0x41200000) {
  16. /* |x| > 10 */
  17. t = 1 + 0/(x + 0x1p-120f);
  18. } else {
  19. t = expm1f(2*x);
  20. t = 1 - 2/(t+2);
  21. }
  22. } else if (w > 0x3e82c578) {
  23. /* |x| > log(5/3)/2 ~= 0.2554 */
  24. t = expm1f(2*x);
  25. t = t/(t+2);
  26. } else {
  27. /* |x| is small */
  28. t = expm1f(-2*x);
  29. t = -t/(t+2);
  30. }
  31. return sign ? -t : t;
  32. }