summaryrefslogtreecommitdiffstats
path: root/lib/libm/src/s_logbl.c
blob: 7de6ede4fd0938a6696334c39821795eec631e61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*	$OpenBSD: s_logbl.c,v 1.1 2008/12/09 20:00:35 martynas Exp $	*/
/*
 * From: @(#)s_ilogb.c 5.1 93/09/24
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunPro, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

#include <sys/types.h>
#include <machine/ieee.h>
#include <float.h>
#include <limits.h>
#include <math.h>

long double
logbl(long double x)
{
	union {
		long double e;
		struct ieee_ext bits;
	} u;
	unsigned long m;
	int b;

	u.e = x;
	if (u.bits.ext_exp == 0) {
		if ((u.bits.ext_fracl
#ifdef EXT_FRACLMBITS
			| u.bits.ext_fraclm
#endif /* EXT_FRACLMBITS */
#ifdef EXT_FRACHMBITS
			| u.bits.ext_frachm
#endif /* EXT_FRACHMBITS */
			| u.bits.ext_frach) == 0) {	/* x == 0 */
			u.bits.ext_sign = 1;
			return (1.0L / u.e);
		}
		/* denormalized */
		if (u.bits.ext_frach == 0
#ifdef EXT_FRACHMBITS
			&& u.bits.ext_frachm == 0
#endif
			) {
			m = 1lu << (EXT_FRACLBITS - 1);
			for (b = EXT_FRACHBITS; !(u.bits.ext_fracl & m); m >>= 1)
				b++;
#if defined(EXT_FRACHMBITS) && defined(EXT_FRACLMBITS)
			m = 1lu << (EXT_FRACLMBITS - 1);
			for (b += EXT_FRACHMBITS; !(u.bits.ext_fraclm & m);
				m >>= 1)
				b++;
#endif /* defined(EXT_FRACHMBITS) && defined(EXT_FRACLMBITS) */
		} else {
			m = 1lu << (EXT_FRACHBITS - 1);
			for (b = 0; !(u.bits.ext_frach & m); m >>= 1)
				b++;
#ifdef EXT_FRACHMBITS
			m = 1lu << (EXT_FRACHMBITS - 1);
			for (; !(u.bits.ext_frachm & m); m >>= 1)
				b++;
#endif /* EXT_FRACHMBITS */
		}
#ifdef EXT_IMPLICIT_NBIT
		b++;
#endif
		return ((long double)(LDBL_MIN_EXP - b - 1));
	}
	if (u.bits.ext_exp < (LDBL_MAX_EXP << 1) - 1)	/* normal */
		return ((long double)(u.bits.ext_exp - LDBL_MAX_EXP + 1));
	else						/* +/- inf or nan */
		return (x * x);
}