blob: 3ec59f22ead3853feded846f4df05b8a86209fde [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * ====================================================
3 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
4 *
5 * Developed at SunPro, a Sun Microsystems, Inc. business.
6 * Permission to use, copy, modify, and distribute this
7 * software is freely granted, provided that this notice
8 * is preserved.
9 * ====================================================
10 */
11
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080012/*
13 * trunc(x)
14 * Return x rounded toward 0 to integral value
15 * Method:
16 * Bit twiddling.
17 * Exception:
18 * Inexact flag raised if x not equal to trunc(x).
19 */
20
Elliott Hughesa0ee0782013-01-30 19:06:37 -080021#include <float.h>
22
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080023#include "math.h"
24#include "math_private.h"
25
26static const double huge = 1.0e300;
27
28double
29trunc(double x)
30{
31 int32_t i0,i1,j0;
Elliott Hughesa0ee0782013-01-30 19:06:37 -080032 u_int32_t i;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080033 EXTRACT_WORDS(i0,i1,x);
34 j0 = ((i0>>20)&0x7ff)-0x3ff;
35 if(j0<20) {
36 if(j0<0) { /* raise inexact if x != 0 */
37 if(huge+x>0.0) {/* |x|<1, so return 0*sign(x) */
38 i0 &= 0x80000000U;
39 i1 = 0;
40 }
41 } else {
42 i = (0x000fffff)>>j0;
43 if(((i0&i)|i1)==0) return x; /* x is integral */
44 if(huge+x>0.0) { /* raise inexact flag */
45 i0 &= (~i); i1=0;
46 }
47 }
48 } else if (j0>51) {
49 if(j0==0x400) return x+x; /* inf or NaN */
50 else return x; /* x is integral */
51 } else {
52 i = ((u_int32_t)(0xffffffff))>>(j0-20);
53 if((i1&i)==0) return x; /* x is integral */
54 if(huge+x>0.0) /* raise inexact flag */
55 i1 &= (~i);
56 }
57 INSERT_WORDS(x,i0,i1);
58 return x;
59}
Elliott Hughesa0ee0782013-01-30 19:06:37 -080060
61#if LDBL_MANT_DIG == 53
62__weak_reference(trunc, truncl);
63#endif