blob: 3b1127f972865b418e29de0d2df5647fa2d44896 (
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
|
// round.hh -- template for rounding floating point values
// $Id$
//
// *** Implementation Notes ***
// round::to_integer
// round::floor
// round::ceiling
//
// *** instantiations of round template for <float> and <double>
//
#include "stdc.h"
#include "util++.hh"
//*****************************************************************************
// round.hh -- template for rounding floating point values
//*****************************************************************************
//
// *** Implementation Notes ***
//
// We assume throughout this code that C++'s "built-in" conversion
// from <fpt> to integer takes the floor, at least for zero or positive
// values.
//
//*****************************************************************************
// round to nearest integer, up for exact tie
template <class fpt>
int round<fpt>::to_integer(fpt 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 <class fpt>
int round<fpt>::floor(fpt x)
{
return (x >= 0.0)
? int(x)
: - ceiling(-x);
}
//*****************************************************************************
template <class fpt>
int round<fpt>::ceiling(fpt x)
{
return (x >= 0.0)
? int(x) + (x != fpt(int(x)))
: - floor(-x);
}
//*****************************************************************************
// *** instantiations of round template for <float> and <double>
//*****************************************************************************
// instantiation for <float>
template class round<float>;
// instantiations for <double>
template class round<double>;
|