Uni20
Asynchronous tensor and runtime library.
Loading...
Searching...
No Matches
core/precision.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <limits>
5#include <stdexcept>
6
7namespace uni20
8{
9
13class Precision {
14 public:
15 using bit_count_type = std::int64_t;
17 static constexpr Precision exact() noexcept { return Precision(0); }
18 constexpr bool is_exact() const noexcept { return bits_ == 0; }
19
21 static constexpr Precision bits(bit_count_type count)
22 {
23 if (count < 1) throw std::invalid_argument("Precision::bits: unsupported significand size");
24 return Precision(count);
25 }
26
29 static constexpr Precision decimal_digits(std::int64_t count)
30 {
31 if (count <= 0) throw std::invalid_argument("Precision::decimal_digits: expected a positive count");
32 auto const digits = static_cast<std::uint64_t>(count);
33 auto const major = digits / 100000;
34 auto const minor = ((digits % 100000) * 332193 + 99999) / 100000;
35 auto const maximum = static_cast<std::uint64_t>(std::numeric_limits<bit_count_type>::max());
36 if (major > maximum / 332193 || minor > maximum - major * 332193)
37 throw std::invalid_argument("Precision::decimal_digits: unsupported significand size");
38 return Precision::bits(static_cast<bit_count_type>(major * 332193 + minor));
39 }
40
43 constexpr bit_count_type bit_count() const
44 {
45 if (this->is_exact())
46 throw std::logic_error("exact arithmetic requires an explicit finite working precision here");
47 return bits_;
48 }
49 constexpr bool operator==(Precision const&) const = default;
50
51 private:
52 explicit constexpr Precision(bit_count_type bits) : bits_(bits) {}
53 bit_count_type bits_;
54};
55
58{
59 if (a.is_exact()) return b;
60 if (b.is_exact()) return a;
61 if (a != b) throw std::invalid_argument("mixed precisions require explicit conversion");
62 return a;
63}
64
65} // namespace uni20
Exact arithmetic or an explicit binary working precision.
Definition core/precision.hpp:13
constexpr bool operator==(Precision const &) const =default
static constexpr Precision bits(bit_count_type count)
Select a positive binary significand size.
Definition core/precision.hpp:21
constexpr bit_count_type bit_count() const
Number of binary significand bits.
Definition core/precision.hpp:43
std::int64_t bit_count_type
Definition core/precision.hpp:15
constexpr bool is_exact() const noexcept
Definition core/precision.hpp:18
static constexpr Precision decimal_digits(std::int64_t count)
Request at least this many decimal digits of significand precision.
Definition core/precision.hpp:29
static constexpr Precision exact() noexcept
No approximation has been selected; rational arithmetic remains exact.
Definition core/precision.hpp:17
Definition async/async.hpp:26
constexpr Precision common_precision(Precision a, Precision b)
Combine precisions, treating exact values as neutral and rejecting unequal finite precisions.
Definition core/precision.hpp:57