Skip to content

Commit 6c1a674

Browse files
committed
Factor out the number rounding logic for the array printer
1 parent b9fcdfc commit 6c1a674

1 file changed

Lines changed: 30 additions & 4 deletions

File tree

src/TiledArray/tensor/print.ipp

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,33 @@ namespace TiledArray {
3333

3434
namespace detail {
3535

36+
class NumberRounder {
37+
public:
38+
NumberRounder(int precision) noexcept : precision_{precision} {}
39+
40+
[[nodiscard]] auto round(std::floating_point auto val) const noexcept {
41+
return std::abs(val) <
42+
(0.5 * std::pow(static_cast<decltype(val)>(10), -precision_))
43+
? 0
44+
: val;
45+
}
46+
47+
template <typename T>
48+
requires detail::is_complex_v<T> && std::floating_point<typename T::value_type>
49+
[[nodiscard]] auto round(T const& val) const noexcept {
50+
using std::imag;
51+
using std::real;
52+
return T{round(real(val)), round(imag(val))};
53+
}
54+
55+
template <typename T>
56+
requires (!(std::floating_point<T> || detail::is_complex_v<T>))
57+
[[nodiscard]] auto round(T const& val) const noexcept { return val; }
58+
59+
private:
60+
int precision_;
61+
};
62+
3663
// Class to print n-dimensional arrays in NumPy style but with curly braces
3764
template <typename T, typename Index, typename Char, typename CharTraits>
3865
void NDArrayPrinter::printArray(const T* data, const std::size_t order,
@@ -48,12 +75,11 @@ void NDArrayPrinter::printArray(const T* data, const std::size_t order,
4875
os << std::basic_string<Char, CharTraits>(extra_indentation, ' ');
4976
os << "{";
5077

78+
auto rounder = NumberRounder{precision};
79+
5180
for (size_t i = 0; i < extents[level]; ++i) {
5281
if (level == order - 1) {
53-
auto value = data[offset + i * strides[level]];
54-
if constexpr (std::is_floating_point_v<decltype(value)>) {
55-
value = std::abs(value) < (0.5 / (std::pow(10, precision))) ? 0 : value;
56-
}
82+
auto value = rounder.round(data[offset + i * strides[level]]);
5783
// At the deepest level, print the actual values
5884
os << std::fixed << std::setprecision(precision) << std::setw(width) << std::setfill(Char(' ')) << value;
5985
if (i < extents[level] - 1) {

0 commit comments

Comments
 (0)