File size: 1,613 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tolerance-derived quantizer; all four numeric options display with one decimal place."""
import math
from dataclasses import dataclass

from tools.evaluation import np_answers


@dataclass(frozen=True)
class Format:
    digits: int

    def value(self, value):
        """Quantize before candidate spacing, normalizing signed zero."""
        if isinstance(value, list):
            return [self.value(x) for x in value]
        rounded = float(f'{value:.{self.digits-1}e}')
        return 0. if rounded == 0 else rounded

    def text(self, value):
        """Plain decimal with one digit after the point (options are already quantized), also per vector component."""
        if isinstance(value, list):
            return '[' + ', '.join(self.text(x) for x in value) + ']'
        text = f"{value:.1f}"
        return '0.0' if text == '-0.0' else text


def formatter(truth, rule):
    """Use the least precision whose worst rounding error fits half a tolerance.

    The logarithmic rule needs a relative bound; other rules use their original
    truth's radius. Planar components share the same precision and error budget.
    """
    if rule['kind'] == 'log_ratio':
        digits = max(1, math.ceil(1-math.log10(2*(1-1/rule['factor']))))
    else:
        vector = isinstance(truth, list)
        magnitude = max(map(abs, truth)) if vector else abs(truth)
        tau = np_answers.radius(truth, rule)[0]
        budget = tau / (2*math.sqrt(2) if vector else 2)
        digits = max(1, math.ceil(math.floor(math.log10(magnitude)) - math.log10(2*budget) + 1)) if magnitude else 1
    return Format(digits)