~cnx/palace

ref: 708f23b35a7e232273ba0a63a65b3ef778a84540 palace/tests/unit/fmath.py -rw-r--r-- 2.1 KiB
708f23b3 — Ngô Ngọc Đức Huy Write tutorial for source effect 1 year, 8 months ago
                                                                                
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
# Single-precision floating-point math
# Copyright (C) 2020  Nguyễn Gia Phong
#
# This file is part of palace.
#
# palace is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# palace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with palace.  If not, see <https://www.gnu.org/licenses/>.

"""This module provides access to mathematical functions
for single-precision floating-point numbers.
"""
__all__ = ['FLT_MAX', 'allclose', 'isclose']

from math import isclose as _isclose
from typing import Any, Callable, Sequence

FLT_EPSILON: float = 2.0 ** -23
FLT_MAX: float = 2.0**128 - 2.0**104


def isclose(a: float, b: float) -> bool:
    """Determine whether two single-precision floating-point numbers
    are close in value.

    For the values to be considered close, the relative difference
    between them must be smaller than FLT_EPSILON.

    -inf, inf and NaN behave similarly to the IEEE 754 Standard.
    That is, NaN is not close to anything, even itself.
    inf and -inf are only close to themselves.
    """
    return _isclose(a, b, rel_tol=FLT_EPSILON)


def allclose(a: Sequence[float], b: Sequence[float],
             close: Callable[[Any, Any], bool] = isclose) -> bool:
    """Determine whether two sequences of single-precision
    floating-point numbers are close in value.

    For the values to be considered close, the relative difference
    between them must be smaller than FLT_EPSILON.

    -inf, inf and NaN behave similarly to the IEEE 754 Standard.
    That is, NaN is not close to anything, even itself.
    inf and -inf are only close to themselves.
    """
    return type(a) is type(b) and all(map(close, a, b))