aboutsummaryrefslogtreecommitdiff
path: root/src/jtutil/round.cc
blob: 3c2d7e66f60adca766f57490882e28246b622db6 (plain)
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
78
79
80
81
82
// round.hh -- template for rounding floating point values
// $Header$
//
// *** Implementation Notes ***
// jtutil::round::to_integer
// jtutil::round::floor
// jtutil::round::ceiling
//
// ***** template instantiations *****
//

#include <stdlib.h>

#include "stdc.h"
#include "util.hh"

// everything in this file is inside these namespaces
namespace AHFinderDirect
	  {
namespace jtutil
	  {

//******************************************************************************
//******************************************************************************
//******************************************************************************

//
// *** Implementation Notes ***
//
// We assume throughout this code that C++'s "built-in" conversion
// from <fp_t> to integer takes the floor, at least for zero or positive
// values.
//

//******************************************************************************

// round to nearest integer, up for exact tie
template <typename fp_t>
int round<fp_t>::to_integer(fp_t x)
{
return (x >= 0.0)
       ? int(x + 0.5)		// eg 3.6 --> int(4.1) = 4
       : - int( (-x) + 0.5 );	// eg -3.6 --> - int(4.1) = -4
}

//******************************************************************************

template <typename fp_t>
int round<fp_t>::floor(fp_t x)
{
return (x >= 0.0)
       ? int(x)
       : - ceiling(-x);
}

//******************************************************************************

template <typename fp_t>
int round<fp_t>::ceiling(fp_t x)
{
return (x >= 0.0)
       ? int(x) + (x != fp_t(int(x)))
       : - floor(-x);
}

//******************************************************************************
//******************************************************************************
//******************************************************************************

//
// ***** template instantiations *****
//

template class round<float>;
template class round<double>;

//******************************************************************************
//******************************************************************************
//******************************************************************************

	  }	// namespace jtutil
	  }	// namespace AHFinderDirect