aboutsummaryrefslogtreecommitdiff
path: root/src/jtutil/round.cc
diff options
context:
space:
mode:
Diffstat (limited to 'src/jtutil/round.cc')
-rw-r--r--src/jtutil/round.cc66
1 files changed, 66 insertions, 0 deletions
diff --git a/src/jtutil/round.cc b/src/jtutil/round.cc
new file mode 100644
index 0000000..3b1127f
--- /dev/null
+++ b/src/jtutil/round.cc
@@ -0,0 +1,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>;