tanhf.c 653 字节
Newer Older
R
Rich Felker 已提交
1 2 3 4
#include "libm.h"

float tanhf(float x)
{
5 6 7 8
	union {float f; uint32_t i;} u = {.f = x};
	uint32_t w;
	int sign;
	float t;
R
Rich Felker 已提交
9

10 11 12 13 14
	/* x = |x| */
	sign = u.i >> 31;
	u.i &= 0x7fffffff;
	x = u.f;
	w = u.i;
R
Rich Felker 已提交
15

16 17 18 19
	if (w > 0x3f0c9f54) {
		/* |x| > log(3)/2 ~= 0.5493 or nan */
		if (w > 0x41200000) {
			/* |x| > 10 */
20
			t = 1 + 0/x;
R
Rich Felker 已提交
21
		} else {
22 23
			t = expm1f(2*x);
			t = 1 - 2/(t+2);
R
Rich Felker 已提交
24
		}
25 26 27 28
	} else if (w > 0x3e82c578) {
		/* |x| > log(5/3)/2 ~= 0.2554 */
		t = expm1f(2*x);
		t = t/(t+2);
29 30
	} else if (w >= 0x00800000) {
		/* |x| >= 0x1p-126 */
31 32
		t = expm1f(-2*x);
		t = -t/(t+2);
33 34 35 36
	} else {
		/* |x| is subnormal */
		FORCE_EVAL(x*x);
		t = x;
R
Rich Felker 已提交
37
	}
38
	return sign ? -t : t;
R
Rich Felker 已提交
39
}