diff --git a/functional_algorithms/__init__.py b/functional_algorithms/__init__.py index e98d12b..e48cb02 100644 --- a/functional_algorithms/__init__.py +++ b/functional_algorithms/__init__.py @@ -20,3 +20,4 @@ from .restrict import restrict from .signatures import filter_signatures from . import fpu +from .typesystem import Type diff --git a/functional_algorithms/context.py b/functional_algorithms/context.py index ffa0121..6b4cb02 100644 --- a/functional_algorithms/context.py +++ b/functional_algorithms/context.py @@ -1,14 +1,37 @@ +import contextlib import inspect import sys import types import typing import warnings from collections import defaultdict -from .utils import UNSPECIFIED, boolean_types, float_types, complex_types -from .expr import Expr, make_constant, make_symbol, make_apply, known_expression_kinds +from .utils import UNSPECIFIED, boolean_types, float_types, complex_types, integer_types +from .expr import Expr, make_constant, make_symbol, make_apply, known_expression_kinds, make_series from .typesystem import Type +class Parameters(dict): + """A dictionary that call method enables context manager support to + temporarily modify dictionary content. + """ + + def __call__(self, **items): + + @contextlib.contextmanager + def manager(items): + prev_items = dict((k, v) for k, v in self.items() if k in items) + new_keys = {k for k in items if k not in self} + try: + self.update(items) + yield self + finally: + self.update(prev_items) + for k in new_keys: + self.pop(k) + + return manager(items) + + class Context: def __init__(self, paths=[], enable_alt=None, default_constant_type=None, parameters=None): @@ -39,7 +62,7 @@ def __init__(self, paths=[], enable_alt=None, default_constant_type=None, parame self._enable_alt = enable_alt self._default_constant_type = default_constant_type self._default_like = None - self.parameters = parameters or {} + self.parameters = Parameters(parameters or {}) if "using" not in self.parameters: self.parameters["using"] = set() @@ -248,8 +271,12 @@ def constant(self, value, like_expr=UNSPECIFIED): like_expr = self.symbol("_float_value", type(value)) elif isinstance(value, complex_types): like_expr = self.symbol("_complex_value", type(value)) + elif isinstance(value, integer_types): + like_expr = self.symbol("_integer_value", type(value)) else: like_expr = self.default_like + if like_expr is int: + like_expr = self.symbol("_integer_value", int) return make_constant(self, value, like_expr) def call(self, func, args): @@ -317,8 +344,10 @@ def floor_divide(self, x, y): def pow(self, x, y): if isinstance(y, float) and y == 0.5: return self.sqrt(x) - if isinstance(y, int) and y == 2: - return self.square(x) + if isinstance(y, int): + if y == 2: + return self.square(x) + return Expr(self, "pow", (x, self.constant(y, int))) return Expr(self, "pow", (x, y)) def logical_and(self, x, y): @@ -341,8 +370,8 @@ def logical_not(self, x): Not = logical_not - def bitwise_invert(self): - return Expr(self, "bitwise_invert", (self,)) + def bitwise_invert(self, x): + return Expr(self, "bitwise_invert", (x,)) invert = bitwise_invert @@ -516,3 +545,19 @@ def downcast(self, x): def is_finite(self, x): return Expr(self, "is_finite", (x,)) + + def series(self, *terms, **params): + unit_index = params.get("unit_index", 0) + scaling_exp = params.get("scaling_exp", 0) + return make_series(self, unit_index, scaling_exp, terms) + + def _series(self, terms, params): + return self.series(*terms, **params) + + def _get_series_operands(self, expr): + if expr.kind == "series": + return expr.operands + return expr + + def fma(self, x, y, z): + return Expr(self, "fma", (x, y, z)) diff --git a/functional_algorithms/expr.py b/functional_algorithms/expr.py index 2786ebd..4f2a9d3 100644 --- a/functional_algorithms/expr.py +++ b/functional_algorithms/expr.py @@ -23,7 +23,8 @@ ceil, floor, floor_divide, remainder, round, truncate, copysign, sign, nextafter, upcast, downcast, -is_finite, is_inf, is_posinf, is_neginf, is_nan, is_negzero +is_finite, is_inf, is_posinf, is_neginf, is_nan, is_negzero, +series, fma """.replace( " ", "" ) @@ -80,6 +81,7 @@ def normalize_like(expr): "sqrt", "square", "asin_acos_kernel", + "fma", }: expr = expr.operands[0] elif expr.kind == "absolute" and not expr.operands[0].is_complex: @@ -88,6 +90,8 @@ def normalize_like(expr): expr = expr.operands[0].operands[0] elif expr.kind == "imag" and expr.operands[0].kind == "complex": expr = expr.operands[0].operands[1] + elif expr.kind == "series": + expr = expr.operands[1] else: break return expr @@ -118,20 +122,29 @@ def make_apply(context, name, args, result): return Expr(context, "apply", (name, *args, result)) +def make_series(context, unit_index, scaling_exp, terms): + return Expr(context, "series", ((unit_index, scaling_exp), *terms)) + + def normalize(context, operands): """Convert numbers to constant expressions""" exprs = [operand for operand in operands if isinstance(operand, Expr)] if len(exprs) == 0: ref_operand = context.default_like if ref_operand is None: - raise ValueError("cannot normalize operands with no reference operand or context default constant type") + operand_types = ", ".join(sorted(set([type(operand).__name__ for operand in operands]))) + raise ValueError( + f"cannot normalize operands (of types {operand_types}) with no reference operand or context default constant type" + ) else: ref_operand = exprs[0] new_operands = [] for operand in operands: - if isinstance(operand, (int, float, complex, str)): + if isinstance(operand, (int, float, complex, str, numpy.floating, numpy.complexfloating, numpy.integer)): operand = make_constant(context, operand, ref_operand) + else: + assert isinstance(operand, Expr), type(operand) new_operands.append(operand) return tuple(new_operands) @@ -161,7 +174,7 @@ def toidentifier(value): elif isinstance(value, numpy.floating): try: intvalue = int(value) - except OverflowError: + except (OverflowError, ValueError): intvalue = None if value == intvalue: return value.dtype.kind + toidentifier(intvalue) @@ -201,10 +214,19 @@ def make_ref(expr): elif expr.kind == "absolute": # using abs for BC ref = f"abs_{make_ref(expr.operands[0])}" - else: + elif expr.kind == "series": all_operands_have_ref_name = not [ - 0 for o in expr.operands if not isinstance(expr.operands[0].props.get("reference_name"), str) + 0 for o in expr.operands[1:] if not isinstance(o.props.get("reference_name"), str) ] + if all_operands_have_ref_name: + # for readability + params = [f"minus{p}" if p < 0 else str(p) for p in expr.operands[0]] + lst = [expr.kind] + params + list(map(make_ref, expr.operands[1:])) + ref = "_".join(lst) + else: + ref = f"{expr.kind}_{expr.intkey}" + else: + all_operands_have_ref_name = not [0 for o in expr.operands if not isinstance(o.props.get("reference_name"), str)] if all_operands_have_ref_name: # for readability lst = [expr.kind] + list(map(make_ref, expr.operands)) @@ -315,7 +337,7 @@ def __new__(cls, context, kind, operands): if context.alt is not None and not isinstance(operands[0], Expr): operands = [context.alt.constant(operands[0]), operands[1]] else: - if kind == "select": + if kind in {"select", "series"}: operands = operands[:1] + normalize(context, operands[1:]) else: operands = normalize(context, operands) @@ -338,7 +360,13 @@ def __new__(cls, context, kind, operands): operands = (Expr(context.alt, kind, tuple(constant_operands)), constant_like) kind = "constant" - assert False not in [isinstance(operand, Expr) for operand in operands], operands + if kind == "series": + assert isinstance(operands[0], tuple) and len(operands[0]) == 2, type(operands[0]) + assert isinstance(operands[0][0], int) + assert isinstance(operands[0][1], int) + assert False not in [isinstance(operand, Expr) for operand in operands[1:]], operands + else: + assert False not in [isinstance(operand, Expr) for operand in operands], operands obj.context = context obj.kind = kind @@ -387,6 +415,8 @@ def _compute_serialized(self): value.key if isinstance(value, Expr) else (value, type(value).__name__), like.key, ) + elif self.kind == "series": + r = (self.kind, self.operands[0], *(operand.intkey for operand in self.operands[1:])) else: # Don't use `operand.key` as its size is unbounded and # will lead to large overhead in computing the hash value @@ -467,6 +497,14 @@ def rewrite(self, modifier, *modifiers, deep_first=None, _rewrite_context=None): result = make_apply(self.context, self.operands[0], self.operands[1:-1], body) else: result = self + elif self.kind == "series": + terms = tuple([operand.rewrite(modifier, **rewrite_kwargs) for operand in self.operands[1:]]) + for o1, o2 in zip(terms, self.operands[1:]): + if o1 is not o2: + result = Expr(self.context, self.kind, (self.operands[0], *terms)) + break + else: + result = self else: operands = tuple([operand.rewrite(modifier, **rewrite_kwargs) for operand in self.operands]) for o1, o2 in zip(operands, self.operands): @@ -584,8 +622,13 @@ def __str__(self): return Printer().tostring(self) def __repr__(self): - operands = tuple(f"{o.kind}:{o.intkey}" for o in self.operands) - return f"{type(self).__name__}({self.kind}, {operands}, {self.props})" + if self.kind in {"symbol"}: + operands = tuple(repr(o) for o in self.operands) + elif self.kind in {"series", "constant"}: + operands = (repr(self.operands[0]),) + tuple(f"{o.kind}:{o.intkey}" for o in self.operands[1:]) + else: + operands = tuple(f"{o.kind}:{o.intkey}" for o in self.operands) + return f"{type(self).__name__}({self.kind!r}, {operands}, {self.props})" def __abs__(self): return self.context.absolute(self) @@ -989,12 +1032,16 @@ def is_complex(self): "minimum", "floor_divide", "remainder", + "truncate", + "round", }: return False elif self.kind in {"complex", "conjugate"}: return True elif self.kind in {"add", "subtract", "divide", "multiply", "pow"}: return self.operands[0].is_complex or self.operands[1].is_complex + elif self.kind == "fma": + return self.operands[0].is_complex or self.operands[1].is_complex or self.operands[2].is_complex elif self.kind in { "positive", "negative", @@ -1023,6 +1070,11 @@ def is_complex(self): return self.operands[0].is_complex elif self.kind == "apply": return self.operands[-1].is_complex + elif self.kind == "series": + for o in self.operands[1:]: + if o.is_complex: + return True + return False else: raise NotImplementedError(f"{type(self).__name__}.is_complex not implemented for {self.kind}") @@ -1065,6 +1117,8 @@ def get_type(self): "copysign", "conjugate", "asin_acos_kernel", + "truncate", + "round", }: return self.operands[0].get_type() elif self.kind in { @@ -1080,6 +1134,16 @@ def get_type(self): "atan2", }: return self.operands[0].get_type().max(self.operands[1].get_type()) + elif self.kind == "series": + t = self.operands[1].get_type() + for o in self.operands[2:]: + t = t.max(o.get_type()) + return t + elif self.kind == "fma": + t = self.operands[0].get_type() + for o in self.operands[1:]: + t = t.max(o.get_type()) + return t elif self.kind in {"absolute", "real", "imag"}: t = self.operands[0].get_type() return t.complex_part if t.is_complex else t diff --git a/functional_algorithms/floating_point_algorithms.py b/functional_algorithms/floating_point_algorithms.py index d4df654..352f4b2 100644 --- a/functional_algorithms/floating_point_algorithms.py +++ b/functional_algorithms/floating_point_algorithms.py @@ -6,8 +6,54 @@ """ +def fma_native(ctx, x: float, y: float, z: float): + """Evaluate x * y + z.""" + return x * y + z + + +def fma_upcast(ctx, x: float, y: float, z: float): + """Evaluate x * y + z using upcast of operands.""" + x_ = ctx.upcast(x) + y_ = ctx.upcast(y) + z_ = ctx.upcast(z) + return ctx.downcast(x_ * y_ + z_) + + +def fma_upcast2(ctx, x: float, y: float, z: float): + """Evaluate x * y + z using double upcast of operands.""" + x_ = ctx.upcast2(x) + y_ = ctx.upcast2(y) + z_ = ctx.upcast2(z) + return ctx.downcast2(x_ * y_ + z_) + + +def get_number(ctx, expr): + import functional_algorithms as fa + + if isinstance(expr, fa.utils.number_types): + return expr + if hasattr(expr, "kind"): + if expr.kind == "constant" and isinstance(expr.operands[0], fa.utils.number_types): + typ = ctx.parameters.get("type") + dtype = None if typ is None else typ.asdtype() + if dtype is not None: + return dtype(expr.operands[0]) + + def get_largest(ctx, x: float): - largest = ctx.constant("largest", x) + import functional_algorithms as fa + + if isinstance(x, fa.utils.float_types): + import numpy + + return numpy.finfo(type(x)).max + + typ = ctx.parameters.get("type") + if typ is not None: + largest_value = typ.get_largest() or "largest" + else: + largest_value = "largest" + largest = ctx.constant(largest_value, x) if hasattr(largest, "reference"): largest = largest.reference("largest") return largest @@ -70,6 +116,7 @@ def get_veltkamp_splitter_constants(ctx, largest: float): Using `largest` to detect the floating point type: float16, float32, or float64. """ + import functional_algorithms as fa fp64 = ctx.constant(2 ** (54 // 2) + 1, largest) fp32 = ctx.constant(2 ** (24 // 2) + 1, largest) @@ -83,6 +130,20 @@ def get_veltkamp_splitter_constants(ctx, largest: float): fp32 = ctx.constant(0.5 ** (24 // 2), largest) fp16 = ctx.constant(0.5 ** (12 // 2), largest) invN = ctx.select(largest > 1e308, fp64, ctx.select(largest > 1e38, fp32, fp16)) + + if hasattr(largest, "operands") and isinstance(largest.operands[0], fa.utils.number_types): + if largest.operands[0] > 1e308: + C = C.operands[1] + N = N.operands[1] + invN = invN.operands[1] + elif largest.operands[0] > 1e38: + C = C.operands[2].operands[1] + N = N.operands[2].operands[1] + invN = invN.operands[2].operands[1] + else: + C = C.operands[2].operands[2] + N = N.operands[2].operands[2] + invN = invN.operands[2].operands[2] if hasattr(C, "reference"): C = C.reference("veltkamp_C", force=True) N = N.reference("veltkamp_N", force=True) @@ -129,12 +190,16 @@ def get_is_power_of_two_constants(ctx, largest: float): fp64 = ctx.constant(1 << (53 - 1), largest) fp32 = ctx.constant(1 << (24 - 1), largest) fp16 = ctx.constant(1 << (11 - 1), largest) - Q = ctx.select(largest > 1e308, fp64, ctx.select(largest > 1e38, fp32, fp16)).reference("Qispowof2", force=True) + Q = ctx.select(largest > 1e308, fp64, ctx.select(largest > 1e38, fp32, fp16)) fp64 = ctx.constant(1 << (53 - 1) + 1, largest) fp32 = ctx.constant(1 << (24 - 1) + 1, largest) fp16 = ctx.constant(1 << (11 - 1) + 1, largest) - P = ctx.select(largest > 1e308, fp64, ctx.select(largest > 1e38, fp32, fp16)).reference("Pispowof2", force=True) + P = ctx.select(largest > 1e308, fp64, ctx.select(largest > 1e38, fp32, fp16)) + + if hasattr(Q, "reference"): + Q = Q.reference("Qispowof2", force=True) + P = P.reference("Pispowof2", force=True) return Q, P @@ -172,7 +237,20 @@ def nextdown(ctx, x: float): return next(ctx, x, up=False) -def split_veltkamp(ctx, x, C=None, scale=False): +def _split_veltkamp(ctx, x, C, N): + if N is not None: + x_orig = x + x = x / N + g = C * x + d = g - x + xh = g - d + xl = x - xh + if N is not None: + xh, xl = xh * N, xl * N + return xh, xl + + +def split_veltkamp(ctx, x, C=None, scale=None): """Veltkamp splitter: x = xh + xl @@ -185,7 +263,7 @@ def split_veltkamp(ctx, x, C=None, scale=False): where p is the precision of the floating point system, xh and xl significant parts fit into p / 2 bits. - It is assumed that the aritmetical operations use rounding to + It is assumed that the arithmetical operations use rounding to nearest and C * x does not overflow. If scale is True, large abs(x) values are normalized with `(C - 1)` to increase the domain of appicability. @@ -196,28 +274,82 @@ def split_veltkamp(ctx, x, C=None, scale=False): abs(x) <= largest / C otherwise """ + import numpy + + largest = get_largest(ctx, x) if C is None: - C, N, invN = get_veltkamp_splitter_constants(ctx, get_largest(ctx, x)) - elif scale: - one = ctx.constant(1, x) - N = C - one - invN = one / N + C, N, _ = get_veltkamp_splitter_constants(ctx, largest) + else: + if ctx is None: + N = C - type(C)(1) + else: + N = C - ctx.constant(1, x) + + x_ = get_number(ctx, x) + largest_ = get_number(ctx, largest) + + if x_ is not None and largest_ is not None: + C_ = get_number(ctx, C) + N_ = C_ - type(C_)(1) + assert C_ is not None + assert N_ is not None + if scale is None: + scale = abs(x_) * C_ > largest_ + elif abs(x_) <= 1: + scale = False + if not numpy.isfinite(x_): + xh_, xl_ = x_, 0 + else: + one = type(C_)(1) + xh_, xl_ = _split_veltkamp(ctx, x_, C_, (N_ if scale else None)) + if not numpy.isfinite(xh_): + import functional_algorithms as fa + + # Warning: result is not a Veltkamp split! + fa.utils.warn_once(f"split_veltkamp({x_}) not finite: returning ({x_}, 0)") + xh_, xl_ = x_, 0 + if ctx is None: + return xh_, xl_ + return ctx.constant(xh_, x), ctx.constant(xl_, x) + + return _split_veltkamp(ctx, x, C, ctx.select(abs(x) < 1, ctx.constant(1, x), N) if scale else None) + + +def split_veltkamp2(ctx, x): + """2nd Veltkamp splitter: + + x = xh + xl + xh + + Different from split_veltkamp, 2nd Veltkamp splitter can be used + for large inputs. + + Note that for large x, `xh + xh` may overflow but `xh + xl + xh` + will never overflow. - if scale: - N = ctx.select(abs(x) < one, one, N) - invN = ctx.select(abs(x) < one, one, invN) + Domain of applicability: - x_n = x * invN if scale else x + smallest_normal * (2 * C - 2) <= abs(x) <= largest - g = C * x_n - d = g - x_n - xh = g - d - xl = x_n - xh + where - return (xh * N, xl * N) if scale else (xh, xl) + C = 1 + 2 ** ceil(p / 2) + and p is the precision of the floating point system. + """ + C, _, _ = get_veltkamp_splitter_constants(ctx, get_largest(ctx, x)) + S = C - ctx.constant(1, x) + S2 = S + S + # S is power of 2, so is S2, hence x / S2 is exact when it does + # not underflow: + xh, xl = split_veltkamp(ctx, x / S2, C=C, scale=False) + return xh * S, xl * S2 -def mul_dw(ctx, x, y, xh, xl, yh, yl): + +def mul_veltkamp(ctx, x, y, xh, xl, yh, yl): + """Veltkamp's multiplication + + mul_veltkamp and mul12 are equivalent accuracy-wise. + """ xyh = x * y t1 = (-xyh) + xh * yh t2 = t1 + xh * yl @@ -226,8 +358,34 @@ def mul_dw(ctx, x, y, xh, xl, yh, yl): return xyh, xyl +def mul_dw(ctx, xh, xl, yh, yl): + """Dekker's multiplication + + mul_veltkamp and mul12 are equivalent accuracy-wise. + + References: + http://resolver.sub.uni-goettingen.de/purl?GDZPPN001170007 + https://gdz.sub.uni-goettingen.de/download/pdf/PPN362160546_0018/PPN362160546_0018.pdf + """ + p = xh * yh + q = xh * yl + xl * yh + rh = p + q + rl = p - rh + q + xl * yl + return rh, rl + + +def div_dw(ctx, xh, xl, yh, yl): + """Dekker's division""" + q = xh / yh + th, tl = mul_dekker(ctx, q, yh) + l = ((((xh - th) - tl) + xl) - q * yl) / yh + rh = q + l + rl = q - rh + l + return rh, rl + + def mul_dekker(ctx, x, y, C=None): - """Dekker product: + """Dekker's product: x * y = xyh + xyl @@ -259,7 +417,260 @@ def mul_dekker(ctx, x, y, C=None): C = get_veltkamp_splitter_constant(ctx, largest) xh, xl = split_veltkamp(ctx, x, C) yh, yl = split_veltkamp(ctx, y, C) - return mul_dw(ctx, x, y, xh, xl, yh, yl) + if 1: + return mul_dw(ctx, xh, xl, yh, yl) + return mul_veltkamp(ctx, x, y, xh, xl, yh, yl) + + +def div_dekker(ctx, x, y, C=None): + """Dekker's divison: + + x / y = xyh + xyl + """ + if C is None: + largest = get_largest(ctx, x) + C = get_veltkamp_splitter_constant(ctx, largest) + xh, xl = split_veltkamp(ctx, x, C) + yh, yl = split_veltkamp(ctx, y, C) + + if yh.kind == "constant": + import numpy + + if numpy.isinf(yh.operands[0]): + # Warning: x / inf -> 0 + return ctx.constant(0, x), ctx.constant(0, x) + + xyh, xyl = div_dw(ctx, xh, xl, yh, yl) + return xyh, xyl + + +# TODO: sqrt_dekker + + +def _div_series_scalar(ctx, x, y): + assert type(y) is not tuple + + terms = [] + (index1, sexp1), terms1 = x[0], x[1:] + for n in range(len(terms1)): + if ctx.parameters.get("series_uses_dekker"): + _terms_add(ctx, terms, n, *div_dekker(ctx, terms1[n], y)) + else: + _terms_add(ctx, terms, n, terms1[n] / y) + return ctx._series(tuple(terms), dict(unit_index=index1, scaling_exp=sexp1)) + + +def _mul_series_series(ctx, x, y): + (index1, sexp1), terms1 = x[0], x[1:] + (index2, sexp2), terms2 = y[0], y[1:] + assert sexp1 == sexp2, (sexp1, sexp2) + + terms = [] + for n in range(len(terms1) + len(terms2) - 1): + for i, x in enumerate(terms1): + for j, y in enumerate(terms2): + if i + j == n: + if ctx.parameters.get("series_uses_dekker"): + _terms_add(ctx, terms, n, *mul_dekker(ctx, x, y)) + else: + _terms_add(ctx, terms, n, x * y) + + return ctx._series(tuple(terms), dict(unit_index=index1 + index2, scaling_exp=sexp1)) + + +def mul_series(ctx, x, y): + """Multiply x and y which may be series.""" + x = ctx._get_series_operands(x) + y = ctx._get_series_operands(y) + if type(x) is tuple: + if type(y) is tuple: + return _mul_series_series(ctx, x, y) + return _mul_series_series(ctx, x, ((0, 0), y)) + elif type(y) is tuple: + return _mul_series_series(ctx, ((0, 0), x), y) + return _mul_series_series(ctx, ((0, 0), x), ((0, 0), y)) + + +def div_series(ctx, x, y): + """Divide x by y where x may be series.""" + x = ctx._get_series_operands(x) + y = ctx._get_series_operands(y) + if type(x) is tuple: + if type(y) is tuple: + assert 0 # not impl + return _div_series_scalar(ctx, x, y) + elif type(y) is tuple: + assert 0 # not impl + return x / y + + +def _terms_add(ctx, terms, index, *operands): + for i, v in enumerate(operands): + if index + i < len(terms): + if 1: + terms[index + i] += v + else: + h, l = add_2sum(ctx, terms[index + i], v) + terms[index + i] = h + if index + i <= len(terms): + terms.append(l) + else: + terms[index + i + 1] += l + else: + assert index + i == len(terms) + terms.append(v) + + +def _add_series_series(ctx, x, y): + + def op(x, y): + if x is None: + return y + if y is None: + return x + if ctx.parameters.get("series_uses_2sum"): + return add_2sum(ctx, x, y) + return x + y + + return _binaryop_series_series(ctx, x, y, op) + + +def _subtract_series_series(ctx, x, y): + + def op(x, y): + if x is None: + return -y + if y is None: + return x + if ctx.parameters.get("series_uses_2sum"): + return add_2sum(ctx, x, -y) + return x - y + + return _binaryop_series_series(ctx, x, y, op) + + +def _binaryop_series_series(ctx, x, y, op): + swapped = False + if x[0][0] < y[0][0]: + x, y = y, x + swapped = True + + (index1, sexp1), terms1 = x[0], x[1:] + (index2, sexp2), terms2 = y[0], y[1:] + assert sexp1 == sexp2, (sexp1, sexp2) + + terms = [] + for n in range(max(len(terms1), index1 - index2 + len(terms2))): + k = n - (index1 - index2) + if n < len(terms1): + if k >= 0 and k < len(terms2): + if swapped: + r = op(terms2[k], terms1[n]) + else: + r = op(terms1[n], terms2[k]) + else: + if swapped: + r = op(None, terms1[n]) + else: + r = op(terms1[n], None) + elif k >= 0 and k < len(terms2): + if swapped: + r = op(terms2[k], None) + else: + r = op(None, terms2[k]) + else: + r = ctx.constant(0, terms1[0]) + if type(r) is tuple: + _terms_add(ctx, terms, n, *r) + else: + _terms_add(ctx, terms, n, r) + return ctx._series(tuple(terms), dict(unit_index=index1, scaling_exp=sexp1)) + + +def add_series(ctx, x, y): + """Add x and y which may be series.""" + + x = ctx._get_series_operands(x) + y = ctx._get_series_operands(y) + + if type(x) is tuple: + if type(y) is tuple: + return _add_series_series(ctx, x, y) + return _add_series_series(ctx, x, ((0, 0), y)) + elif type(y) is tuple: + return _add_series_series(ctx, ((0, 0), x), y) + return _add_series_series(ctx, ((0, 0), x), ((0, 0), y)) + + +def subtract_series(ctx, x, y): + """Subtract y from x which may be series.""" + + x = ctx._get_series_operands(x) + y = ctx._get_series_operands(y) + + if type(x) is tuple: + if type(y) is tuple: + return _subtract_series_series(ctx, x, y) + return _subtract_series_series(ctx, x, ((0, 0), y)) + elif type(y) is tuple: + return _subtract_series_series(ctx, ((0, 0), x), y) + return _subtract_series_series(ctx, ((0, 0), x), ((0, 0), y)) + + +def mul_series_dekker(ctx, x, y, C=None): + """Dekker's product on series: + + sum(x) * sum(y) = sum(xy) + + Series are represented by a tuple + + ((index, sexp), term1, term2, ..., termN) + """ + x = ctx._get_series_operands(x) + y = ctx._get_series_operands(y) + + offset = 10000 + + if type(x) is tuple: + if type(y) is tuple: + assert x[0][1] == y[0][1] + # (x1, x2, ...) * (y1, y2, ...) + # x11h, x11l = mul_dekker(x1, y1) + # x12h, x12l = mul_dekker(x1, y2) + # ... + # xijh == xjih, xijl == xjil + # = (x11h, x11h * x12l + x11l * x12h + x21h * x12h + ..., ...) + # = (..., ... + x[i,j]h, ... + x[i,j]l + x[i+1,j]h + x[i, j+1]h, ... + x[i+1,j]l + x[i,j+1]l + x[i+1,j+1]h, ... + x[i+1,j+1]l, ...) + terms = [] + for i, x_ in enumerate(x[1:]): + for j, y_ in enumerate(y[1:]): + if i + j >= offset: + _terms_add(ctx, terms, i + j, x_ * y_) + else: + _terms_add(ctx, terms, i + j, *mul_dekker(ctx, x_, y_, C=C)) + return ctx._series(tuple(terms), dict(unit_index=x[0][0] + y[0][0], scaling_exp=x[0][1])) + else: + # (x1, x2, ...) * y + # x1h, x1l = mul_dekker(x1, y) + # x2h, x2l = mul_dekker(x2, y) + # ... + # = (x1h, x1l + x2h, x2l + x3h, ..., xNl) + terms = [] + for i, x_ in enumerate(x[1:]): + if i >= offset: + _terms_add(ctx, terms, i, x_ * y) + else: + _terms_add(ctx, terms, i, *mul_dekker(ctx, x_, y, C=C)) + return ctx._series(tuple(terms), dict(unit_index=x[0][0], scaling_exp=x[0][1])) + elif type(y) is tuple: + terms = [] + for i, y_ in enumerate(y[1:]): + if i >= offset: + _terms_add(ctx, terms, i, x * y_) + else: + _terms_add(ctx, terms, i, *mul_dekker(ctx, x, y_, C=C)) + return ctx._series(tuple(terms), dict(unit_index=y[0][0], scaling_exp=y[0][1])) + return ctx._series(mul_dekker(ctx, x, y, C=C), dict(unit_index=0, scaling_exp=0)) def add_2sum(ctx, x, y, fast=False): @@ -365,11 +776,15 @@ def add_3sum(ctx, x, y, z, Q, P, three_over_two): return s, e, t -def add_dw(ctx, xh, xl, yh, yl, Q, P, three_over_two): +def add_dw(ctx, xh, xl, yh, yl, Q=None, P=None, three_over_two=None): """Add two double-word numbers: xh + xl + yh + yl = s """ + if Q is None: + largest = get_largest(ctx, xh) + Q, P = get_is_power_of_two_constants(ctx, largest) + three_over_two = ctx.constant(1.5, largest) sh, sl = add_2sum(ctx, xh, yh) th, tl = add_2sum(ctx, xl, yl) gh, gl = add_2sum(ctx, sl, th) @@ -389,7 +804,7 @@ def add_dw(ctx, xh, xl, yh, yl, Q, P, three_over_two): ) -def add_4sum(ctx, x, y, z, w, Q, P, three_over_two): +def add_4sum(ctx, x, y, z, w, Q=None, P=None, three_over_two=None): """Add four numbers: x + y + z + w = s @@ -402,6 +817,10 @@ def add_4sum(ctx, x, y, z, w, Q, P, three_over_two): Note: The accuracy of `s` is higher than that of `x + y + z + w`. """ + if Q is None: + largest = get_largest(ctx, x) + Q, P = get_is_power_of_two_constants(ctx, largest) + three_over_two = ctx.constant(1.5, largest) xh, xl = add_2sum(ctx, x, y) yh, yl = add_2sum(ctx, z, w) return add_dw(ctx, xh, xl, yh, yl, Q, P, three_over_two) @@ -427,7 +846,7 @@ def dot2(ctx, x, y, z, w, C, Q, P, three_over_two): return add_dw(ctx, xh, xl, yh, yl, Q, P, three_over_two) -def mul_add(ctx, x, y, z, C, Q, P, three_over_two): +def mul_add(ctx, x, y, z, C=None, Q=None, P=None, three_over_two=None): """Multiply and add: x * y + z = s @@ -443,6 +862,11 @@ def mul_add(ctx, x, y, z, C, Q, P, three_over_two): Note: The accuracy of `s` is higher than that of `x * y + z`. """ + if C is None: + largest = get_largest(ctx, x) + C, _, _ = get_veltkamp_splitter_constants(ctx, largest) + Q, P = get_is_power_of_two_constants(ctx, largest) + three_over_two = ctx.constant(1.5, largest) xh, xl = mul_dekker(ctx, x, y, C) # Inlined code of add_dw(xh, xl, c, 0): @@ -638,17 +1062,45 @@ def compensated_horner(ctx, x, coeffs, reverse=True): def fast_exponent_by_squaring(ctx, x, n): """Evaluate x ** n by squaring.""" + zero = ctx.constant(0, x) if n == 0: return ctx.constant(1, x) - if n == 1: + elif n == 1: return x - if n == 2: - return x * x + elif n == 2: + return ctx.fma(x, x, zero) assert n > 0 r = fast_exponent_by_squaring(ctx, x, n // 2) if n % 2 == 0: - return r * r - return r * r * x + return ctx.fma(r, r, zero) + return ctx.fma(ctx.fma(r, r, zero), x, zero) + + +def fast_exponent_by_squaring_dekker(ctx, x, n: int, depth=0): + """Evaluate x ** n by squaring using Dekker's product.""" + if n == 0: + return ctx.constant(1, x) + elif n == 1: + return x + elif n == 2: + if depth == 0: + # `sum(mul_dekker(x, x))` is less accurate than `x * x`. + # However, `sum(mul_dekker(x, mul_dekker(x, x)))` is more + # accurate that `x * x * x`. + return x * x + return mul_series_dekker(ctx, x, x) + else: + # TODO: introduce dekker_inverse and use + # return inverse_dekker(ctx, fast_exponent_by_squaring_dekker(ctx, x, -n)) + # or + # return fast_exponent_by_squaring_dekker(ctx, inverse_dekker(ctx, x), -n) + # which ever has better accuracy properties + assert n > 0, n # unreachable + r = fast_exponent_by_squaring_dekker(ctx, x, n // 2, depth=depth + 1) + y = fast_exponent_by_squaring_dekker(ctx, r, 2, depth=depth + 1) + if n % 2 == 0: + return y + return mul_series_dekker(ctx, x, y) def canonical_scheme(k, N): @@ -674,7 +1126,7 @@ def fast_polynomial(ctx, x, coeffs, reverse=True, scheme=None, _N=None): P(x) = coeffs[N] + coeffs[N - 1] * x + ... + coeffs[0] * x ** N - when reverse is True, otherwise evaluate a polynomial + when reverse is True, otherwise, evaluate a polynomial P(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[N] * x ** N @@ -693,7 +1145,7 @@ def fast_polynomial(ctx, x, coeffs, reverse=True, scheme=None, _N=None): """ if reverse: - return fast_polynomial(ctx, x, reversed(coeffs), reverse=False, scheme=scheme) + return fast_polynomial(ctx, x, list(reversed(coeffs)), reverse=False, scheme=scheme) if scheme is None: scheme = balanced_dac_scheme @@ -702,19 +1154,24 @@ def fast_polynomial(ctx, x, coeffs, reverse=True, scheme=None, _N=None): if _N is None: _N = N + def w(c): + if isinstance(c, type(x)): + return c + return ctx.constant(c, x) + if N == 0: - return ctx.constant(coeffs[0], x) + return w(coeffs[0]) if N == 1: - return ctx.constant(coeffs[0], x) + ctx.constant(coeffs[1], x) * x + return ctx.fma(w(coeffs[1]), x, w(coeffs[0])) d = scheme(N, _N) if d == 0: # evaluate reduced polynomial as it is - s = ctx.constant(coeffs[0], x) + s = w(coeffs[0]) for i in range(1, N): - s += coeffs[i] * fast_exponent_by_squaring(ctx, x, i) + s = ctx.fma(w(coeffs[i]), fast_exponent_by_squaring(ctx, x, i), s) return s # P(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[N] * x ** N @@ -726,7 +1183,117 @@ def fast_polynomial(ctx, x, coeffs, reverse=True, scheme=None, _N=None): a = fast_polynomial(ctx, x, coeffs[d:], reverse=reverse, scheme=scheme, _N=_N) b = fast_polynomial(ctx, x, coeffs[:d], reverse=reverse, scheme=scheme, _N=_N) xd = fast_exponent_by_squaring(ctx, x, d) - return a * xd + b + return ctx.fma(a, xd, b) + + +def fast_polynomial2(ctx, x, coeffs, reverse=True, scheme=None, _N=None): + """Evaluate a polynomial + + P(x) = coeffs[N] + coeffs[N - 1] * (x**2) + ... + coeffs[0] * (x**2) ** N + + when reverse is True, otherwise, evaluate a polynomial + + P(x) = coeffs[0] + coeffs[1] * (x**2) + ... + coeffs[N] * (x**2) ** N + + where `N = len(coeffs) - 1`. + + See also fast_polynomial2. + """ + + if reverse: + return fast_polynomial2(ctx, x, list(reversed(coeffs)), reverse=False, scheme=scheme) + + if scheme is None: + scheme = balanced_dac_scheme + + N = len(coeffs) - 1 + if _N is None: + _N = N + + def w(c): + if isinstance(c, type(x)): + return c + return ctx.constant(c, x) + + if N == 0: + return w(coeffs[0]) + + if N == 1: + return w(coeffs[0]) + x * w(coeffs[1]) * x + + d = scheme(N, _N) + + if d == 0: + # evaluate reduced polynomial as it is + s = w(coeffs[0]) + for i in range(1, N): + c = fast_exponent_by_squaring(ctx, x, i) + s += c * w(coeffs[i]) * c + return s + + # P(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[N] * x ** N + # = A(x) * x ** d + B(x) + # where + # A(x) = coeffs[d] + coeffs[d + 1] * x + ... + coeffs[N] * x ** (N - d) + # B(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[d - 1] * x ** (d - 1) + + a = fast_polynomial2(ctx, x, coeffs[d:], reverse=reverse, scheme=scheme, _N=_N) + b = fast_polynomial2(ctx, x, coeffs[:d], reverse=reverse, scheme=scheme, _N=_N) + xd = fast_exponent_by_squaring(ctx, x, d) + return xd * a * xd + b + + +def fast_polynomial_dekker(ctx, x, coeffs, reverse=True, scheme=None, _N=None): + """Evaluate a polynomial using Dekker's product. + + See also fast_polynomial. + """ + if reverse: + return fast_polynomial_dekker(ctx, x, list(reversed(coeffs)), reverse=False, scheme=scheme) + + if scheme is None: + scheme = balanced_dac_scheme + + N = len(coeffs) - 1 + if _N is None: + _N = N + + def w(c): + if type(c) is tuple: # c is series + return c + if type(x) is tuple: # x is series + x_ = x[1] + else: + x_ = x + if isinstance(c, type(x_)): + return c + return ctx.constant(c, x_) + + if N == 0: + return w(coeffs[0]) + + if N == 1: + return add_series(ctx, w(coeffs[0]), mul_series_dekker(ctx, w(coeffs[1]), x)) + + d = scheme(N, _N) + + if d == 0: + # evaluate reduced polynomial as it is + s = w(coeffs[0]) + for i in range(1, N): + s = add_series(ctx, s, mul_series_dekker(ctx, w(coeffs[i]), fast_exponent_by_squaring_dekker(ctx, x, i))) + return s + + # P(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[N] * x ** N + # = A(x) * x ** d + B(x) + # where + # A(x) = coeffs[d] + coeffs[d + 1] * x + ... + coeffs[N] * x ** (N - d) + # B(x) = coeffs[0] + coeffs[1] * x + ... + coeffs[d - 1] * x ** (d - 1) + + a = fast_polynomial_dekker(ctx, x, coeffs[d:], reverse=reverse, scheme=scheme, _N=_N) + b = fast_polynomial_dekker(ctx, x, coeffs[:d], reverse=reverse, scheme=scheme, _N=_N) + xd = fast_exponent_by_squaring_dekker(ctx, x, d) + return add_series(ctx, b, mul_series_dekker(ctx, a, xd)) def split_tripleword(ctx, x, scale=False): @@ -769,38 +1336,6 @@ def mul_mw(ctx, x, y): return lst -def mul_mw_mod4(ctx, x, y): - zero = ctx.constant(0, x[0]) - one = ctx.constant(1, x[0]) - four = ctx.constant(4, x[0]) - - def rem4(v): - return ctx.trunc(v / four) * four - - total = zero - rest = zero - ss = 0 - for k in reversed(range(len(x) + len(y) - 1)): - s = zero - acc = zero - for i in reversed(range(len(x))): - j = k - i - if j < 0 or j >= len(y): - continue - xy = x[i] * y[j] - xy = xy - rem4(xy) - ss += float(x[i]) * float(y[j]) - s, t = add_2sum(ctx, s, xy, fast=True) - acc += t - rest += acc - total, t = add_2sum(ctx, s, total, fast=True) - total = total - rem4(total) - rest += t - k = ctx.round(total) # % four - r = total - k # % one - return k % four, r, rest - - def mw2dw(ctx, x): """Return multiword as a double-word. @@ -816,10 +1351,97 @@ def mw2dw(ctx, x): return y, t +def argument_reduction_trigonometric_stage1(ctx, x): + """Return y, t such that + + x * (2 / pi) = 4 * N + y + t + + where N is some integral, 0 <= y <= 4, and abs(t) < 1. + """ + import numpy + + if isinstance(x, (numpy.float64, numpy.float32, numpy.float16)): + return argument_reduction_trigonometric_stage1_impl(ctx, type(x), x) + + largest = get_largest(ctx, x) + fp64_y, fp64_t = argument_reduction_trigonometric_stage1_impl(ctx, numpy.float64, x) + fp32_y, fp32_t = argument_reduction_trigonometric_stage1_impl(ctx, numpy.float32, x) + fp16_y, fp16_t = argument_reduction_trigonometric_stage1_impl(ctx, numpy.float16, x) + y = ctx.select(largest > 1e308, fp64_y, ctx.select(largest > 1e38, fp32_y, fp16_y)) + t = ctx.select(largest > 1e308, fp64_t, ctx.select(largest > 1e38, fp32_t, fp16_t)) + return y, t + + +def argument_reduction_trigonometric_stage1_impl(ctx, dtype, x): + import functional_algorithms as fa + + zero = ctx.constant(0, x) + two = ctx.constant(2, x) + four = ctx.constant(4, x) + + two_over_pi_max_length = None + two_over_pi_mw = fa.utils.get_two_over_pi_multiword(dtype, max_length=two_over_pi_max_length) + xh, xl = split_veltkamp2(ctx, x) + r_mw_h = [v * xh for v in two_over_pi_mw] + r_mw_l = [v * xl for v in two_over_pi_mw] + r_mw_h_m4_r = [v - ctx.round(v / two) * two for v in r_mw_h] + r_mw_l_m4_r = [v - ctx.round(v / four) * four for v in r_mw_l] + + y = None + t = None + for zh, zl in zip(reversed(r_mw_h_m4_r), reversed(r_mw_l_m4_r)): + if y is None: + y, t = add_2sum(ctx, zh + zh, zl) + else: + y, th = add_2sum(ctx, y, zh + zh) + y, tl = add_2sum(ctx, y, zl) + t += th + tl + + n1 = ctx.round(y / four) * four + y1 = y - n1 + y = ctx.select(y1 + two < -t, y - (n1 - four), ctx.select(y1 - two > -t, y - (n1 + four), y1)) + return y, t + + +def argument_reduction_trigonometric_stage2_impl(ctx, dtype, y, t): + import functional_algorithms as fa + + k = ctx.round(y) + rmk = y - k + k = ctx.select(k == ctx.constant(4, k), ctx.constant(0, k), k) + + pi2h, pi2l = fa.utils.get_pi_over_two_multiword(dtype) + pi2h = ctx.constant(pi2h, y) + pi2l = ctx.constant(pi2l, y) + + r1h, r1l = mul_dekker(ctx, rmk, pi2h) + r2h, r2l = mul_dekker(ctx, rmk, pi2l) + r3h, r3l = mul_dekker(ctx, t, pi2h) + r4 = t * pi2l + + r, rrl1 = add_2sum(ctx, r1h, r2h, fast=True) + r, rrl2 = add_2sum(ctx, r, r3h, fast=False) + r, rrl3 = add_2sum(ctx, r, r4, fast=True) + s = rrl3 + r3l + rrl2 + r2l + rrl1 + r1l + + return k, r, s + + +def argument_reduction_trigonometric_stages_impl(ctx, dtype, x): + y, t = argument_reduction_trigonometric_stage1_impl(ctx, dtype, x) + k, r, s = argument_reduction_trigonometric_stage2_impl(ctx, dtype, y, t) + + f = abs(x) > ctx.constant("pi", x) / ctx.constant(4, x) + k = ctx.select(f, ctx.select(k < ctx.constant(-0.5, k), k + ctx.constant(4, x), k), ctx.constant(0, x)) + r = ctx.select(f, r, x) + s = ctx.select(f, s, ctx.constant(0, x)) + return k, r, s + + def argument_reduction_trigonometric(ctx, x): """Return k, r, t such that - x = 2 * pi * N + k * pi / 2 + r + t + x = 2 * pi * N + k * pi / 2 + r + s where N is some integral, k is in {0, 1, 2, 3}, and abs(r) < pi / 4. @@ -829,40 +1451,302 @@ def argument_reduction_trigonometric(ctx, x): import numpy if isinstance(x, (numpy.float64, numpy.float32, numpy.float16)): - return argument_reduction_trigonometric_impl(ctx, type(x), x) + return argument_reduction_trigonometric_stages_impl(ctx, type(x), x) largest = get_largest(ctx, x) - fp64_k, fp64_r, fp64_t = argument_reduction_trigonometric_impl(ctx, numpy.float64, x) - fp32_k, fp32_r, fp32_t = argument_reduction_trigonometric_impl(ctx, numpy.float32, x) - fp16_k, fp16_r, fp16_t = argument_reduction_trigonometric_impl(ctx, numpy.float16, x) + fp64_k, fp64_r, fp64_s = argument_reduction_trigonometric_stages_impl(ctx, numpy.float64, x) + fp32_k, fp32_r, fp32_s = argument_reduction_trigonometric_stages_impl(ctx, numpy.float32, x) + fp16_k, fp16_r, fp16_s = argument_reduction_trigonometric_stages_impl(ctx, numpy.float16, x) k = ctx.select(largest > 1e308, fp64_k, ctx.select(largest > 1e38, fp32_k, fp16_k)) r = ctx.select(largest > 1e308, fp64_r, ctx.select(largest > 1e38, fp32_r, fp16_r)) - t = ctx.select(largest > 1e308, fp64_t, ctx.select(largest > 1e38, fp32_t, fp16_t)) - return k, r, t + s = ctx.select(largest > 1e308, fp64_s, ctx.select(largest > 1e38, fp32_s, fp16_s)) + return k, r, s -def argument_reduction_trigonometric_impl(ctx, dtype, x): +def sin_kernel(ctx, k, r, t): + sn = sine_dw(ctx, r, t) + cs = cosine_dw(ctx, r, t) + if k == 0: + return sn + if k == 1: + return cs + if k == 2: + return -sn + if k == 3: + return -cs + assert 0, k # unreachable - import numpy - import functional_algorithms as fa - def make_constant(v): - return ctx.constant(v, x) +def sine_taylor(ctx, x, order=7, split=False): + """Return sine of x using Taylor series approximation: - two = ctx.constant(2, x) - two_over_pi_max_length = {numpy.float16: None, numpy.float32: None, numpy.float64: None}[dtype] - two_over_pi_mw = list(map(make_constant, fa.utils.get_two_over_pi_multiword(dtype, max_length=two_over_pi_max_length))) - pi_over_two_prec = {numpy.float16: 4, numpy.float32: 20, numpy.float64: 40}[dtype] - pi_over_two, pi_over_two_lo = map( - make_constant, fa.utils.get_pi_over_two_multiword(dtype, prec=pi_over_two_prec, max_length=2) + S(x) = x - x ** 3 / 6 + ... + O(x ** (order + 2)) + + If split is True, return `sh, sl` such that + + S(x) = sh + sl + + where the high and low values are obtained from Dekker's split of + `x ** 2`. + + For best accuracy, use the order argument according to the + following table [assuming abs(x) <= p / 4]: + + dtype | order | mean ULP error | numpy comparsion + --------+-------+------------------+----------------- + float16 | 7 | 91 / 14921 | 72 / 14921 + float32 | 9 | 356 / 1_000_000 | 276 / 1_000_000 + float64 | 15 | 56 / 1_000_000 | 5 / 1_000_000 + + For the corresponding order choices, we have + + sine_taylor(x, order, split=False) == sum(*sine_taylor(x, order, split=True)) + """ + + """ + For float16, consider + S(x) = x - x ** 3 / 6 + x ** 5 / 120 + We write + S(x) = P(x * x, C=[x, -x/6, x/120]) + where + P(y, C) = C[0] + C[1] * y + C[2] * y ** 2 + """ + if not split: + zero = ctx.constant(0, x) + C, f = [x], 1 + for i in range(3, order + 1, 2): + f *= -i * (i - 1) + if i >= 5: + C.append(ctx.fma(x, ctx.constant(1 / f, x), zero)) + else: + # The following is required for float16 and float32 when f is + # small and early evaluation of 1/f leads to accuracy loss. + # For float64, there is a very minor accuracy loss. + # + # fh, fl = split_veltkamp(f) + # 1 / f = 1 / (fh + fl) = 1 / fh - fl / fh ** 2 + fl ** 2 / fh ** 3 - ... + # = [a = fl/fh] = 1 / fh - a / fh + a ** 2 / fh - ... + # ~ fma(-a, 1 / fh, 1 / fh) + fh, fl = split_veltkamp(ctx, ctx.constant(f, x)) + a = fl / fh + C.append(ctx.fma(-a, x / fh, x / fh)) + # Horner's scheme is most accurate + xx = ctx.fma(x, x, zero) + return fast_polynomial(ctx, xx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + """ + For float16, consider + x * x = xxh + xxl + which is an exact representation of the square x ** 2. + Let's find + P(xxh + xxl, C) ~ P(xxh, C) + P'(xxh, C) * xxl + = C[0] + C[1] * xxh + C[2] * xxh ** 2 + + (C[1] + 2 * C[2] * xxh) * xxl + = P(xxh, C=C0) + P(xxh, C=C1) * xxl + where + C1 = [i * c for i, c in enumerate(C0) if i > 0] + """ + xxh, xxl = mul_dekker(ctx, x, x) + C0 = [x] + C1 = [] + f = 1 + for i in range(3, order + 1, 2): + C1.append(x / ctx.constant(f * (i + 1), x)) + f *= -i * (i - 1) + C0.append(x / ctx.constant(f, x)) + # Horner's scheme is most accurate + p0 = fast_polynomial(ctx, xxh, C0, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + p1 = fast_polynomial(ctx, xxh, C1, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + return p0, p1 * xxl + + +def cosine_taylor(ctx, x, order=6, split=False, drop_leading_term=False): + """Return sine of x using Taylor series approximation: + + C(x) = 1 - x ** 2 / 2 + x ** 4 / 24 - ... + O(x ** (order + 2)) + = 1 + x**2 * P(x**2, C=[-1/2!, 1/4!, -1/6!, ...]) + + If split is True, return `ch, cl` such that + + C(x) = ch + cl + + where the high and low values are obtained from Dekker's split of + `x ** 2`. + + For best accuracy, use the order argument according to the + following table [assuming abs(x) <= p / 4]: + + dtype | order | mean ULP error | numpy comparsion + --------+-------+-------------------+----------------- + float16 | 7 | 174 / 14921 | 80 / 14921 + float32 | 9 | 1382 / 1_000_000 | 725 / 1_000_000 + float64 | 19 | 146 / 1_000_000 | 0 / 1_000_000 + + For the corresponding order choices, we have + + cosine_taylor(x, order, split=False) == sum(*cosine_taylor(x, order, split=True)) + + To compute cosm1(x), use drop_leading_term=True. + """ + """ + An alternative evaluation scheme: + + C(x) = 1 - x ** 2 / 2 + x ** 4 / 24 - ... + O(x ** (order + 2)) + = 1 + x ** 4 / 4! + ... + - (x ** 2 / 2 + x ** 6 / 6! + x ** 10 / 10!) + = P1(x ** 4, C=C1) - x**2 * P(x**4, C=C2) + + where + + C1 = [1, 1/4!, 1/8!, ...] + C2 = [1/2!, 1/6!, 1/10!, ...] + """ + if not split: + zero = ctx.constant(0, x) + one = ctx.constant(1, x) + if 0: + f = 1 + iC1 = [1] + iC2 = [] + for i in range(2, order, 2): + f *= i * (i - 1) + if i % 4 == 0: + iC1.append(f) + else: + iC2.append(f) + s1 = iC1[-1] + s2 = iC2[-1] + C1 = [s1 // c for c in iC1] + C2 = [s2 // c for c in iC2] + assert len(C1) == len(C2), (C1, C2) + xx = x * x + xxxx = xx * xx + C = [c1 / s1 - x * (c2 / s2) * x for c1, c2 in zip(C1, C2)] + return fast_polynomial( + ctx, xxxx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1] + ) + + f = 1 + xx = ctx.fma(x, x, zero) + C = [] + for i in range(2, order, 2): + f *= -i * (i - 1) + C.append(ctx.fma(xx, ctx.constant(1 / f, x), zero)) + # Horner's scheme is most accurate + p = fast_polynomial(ctx, xx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + if drop_leading_term: + return p + return ctx.fma(one, one, p) + + xxh, xxl = mul_dekker(ctx, x, x) + C0 = [] + C1 = [] + f = 1 + xx = x * x + for i in range(2, order, 2): + C1.append(xx * ctx.constant(1 / (f * (i + 1)), x)) + f *= -i * (i - 1) + C0.append(xx / ctx.constant(f, x)) + # Horner's scheme is most accurate + p0 = fast_polynomial(ctx, xxh, C0, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + p1 = fast_polynomial(ctx, xxh, C1, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1]) + if drop_leading_term: + return p0, p1 * xxl + return ctx.constant(1, x) + p0, p1 * xxl + + +def sine_taylor_dekker(ctx, x, order=7): + """Return sine of x using Taylor series approximation and Dekker's product. + + See also sine_taylor. + """ + C, f = [x], 1 + for i in range(3, order + 1, 2): + f *= -i * (i - 1) + C.append(div_series(ctx, x, ctx.constant(f, x))) + xx = mul_series(ctx, x, x) + # Horner's scheme is most accurate + return fast_polynomial_dekker( + ctx, xx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1] ) - x_tw = split_tripleword(ctx, x, scale=True) - k, y, t = mul_mw_mod4(ctx, x_tw, two_over_pi_mw) - r_hi, tt = add_2sum(ctx, y * pi_over_two, y * pi_over_two_lo + t * pi_over_two, fast=True) - r_lo = t * pi_over_two_lo + tt - r = ctx.select(abs(x) < pi_over_two / two, x, r_hi) - t = ctx.select(abs(x) < pi_over_two / two, ctx.constant(0, x), r_lo) - return k, r, t + + +def cosine_taylor_dekker(ctx, x, order=7, drop_leading_term=False): + """Return cosine of x using Taylor series approximation and Dekker's product. + + See also cosine_taylor. + """ + one = ctx.constant(1, x) + xx = mul_series(ctx, x, x) + if not drop_leading_term: + # P(x**2, Ce=[1, -1/2!, 1/4!, -1/6!, ...]) + C, f = [one], 1 + for i in range(2, order + 1, 2): + f *= -i * (i - 1) + C.append(div_series(ctx, one, ctx.constant(f, x))) + # Horner's scheme is most accurate + return fast_polynomial_dekker( + ctx, xx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1] + ) + else: + # x**2 * P(x**2, C=[-1/2!, 1/4!, -1/6!, ...]) + C, f = [], 1 + for i in range(2, order + 1 - 2, 2): + f *= -i * (i - 1) + C.append(div_series(ctx, xx, ctx.constant(f, x))) + # Horner's scheme is most accurate + return fast_polynomial_dekker( + ctx, xx, C, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme, canonical_scheme][1] + ) + + +def sine_pade(ctx, x, variant=None): + # See https://math.stackexchange.com/questions/2196371/how-to-approximate-sinx-using-pad%C3%A9-approximation + + if variant is None: + variant = 13, 4 + + P, Q = { + # k=2 : p/q = (-1/12096*x^7 + 13/2160*x^5 - 11/72*x^3 + x)/(1/72*x^2 + 1) + (11, 2): ([1, -11 / 72, 13 / 2160, -1 / 12096], [1, 1 / 72]), + # k=3 : p/q = (551/166320*x^5 - 53/396*x^3 + x)/(5/11088*x^4 + 13/396*x^2 + 1) + (11, 3): ([1, -53 / 396, 551 / 166320], [1, 13 / 396, 5 / 11088]), + # k=4 : p/q = (-127/1240*x^3 + x)/(551/9374400*x^6 + 53/22320*x^4 + 239/3720*x^2 + 1) + (11, 4): ([1, -127 / 1240], [1, 239 / 3720, 53 / 22320, 551 / 9374400]), + # k=5 : p/q = (x)/(127/604800*x^8 + 31/15120*x^6 + 7/360*x^4 + 1/6*x^2 + 1) + (11, 5): ([1], [1, 1 / 6, 7 / 360, 31 / 15120, 127 / 604800]), + # k=2 : p/q = (19/19958400*x^9 - 17/138600*x^7 + 3/440*x^5 - 26/165*x^3 + x)/(1/110*x^2 + 1) + (13, 2): ([1, -26 / 165, 3 / 440, -17 / 138600, 19 / 19958400], [1, 1 / 110]), + # k=3 : p/q = (-121/2268000*x^7 + 601/118800*x^5 - 241/1650*x^3 + x)/(19/118800*x^4 + 17/825*x^2 + 1) + (13, 3): ([1, -241 / 1650, 601 / 118800, -121 / 2268000], [1, 17 / 825, 19 / 118800]), + # k=4 : p/q = (12671/4363920*x^5 - 2363/18183*x^3 + x)/(121/16662240*x^6 + 601/872784*x^4 + 445/12122*x^2 + 1) + (13, 4): ([1, -2363 / 18183, 12671 / 4363920], [1, 445 / 12122, 601 / 872784, 121 / 16662240]), + # k=5 : p/q = (-2555/25146*x^3 + x)/(12671/7604150400*x^8 + 2363/31683960*x^6 + 3787/1508760*x^4 + 818/12573*x^2 + 1) + (13, 5): ([1, -2555 / 25146], [1, 818 / 12573, 3787 / 1508760, 2363 / 31683960, 12671 / 7604150400]), + # k=6 : p/q = (x)/(73/3421440*x^10 + 127/604800*x^8 + 31/15120*x^6 + 7/360*x^4 + 1/6*x^2 + 1) + (13, 6): ([1], [1, 1 / 6, 7 / 360, 31 / 15120, 127 / 604800, 73 / 3421440]), + # k=2 : p/q = (1/24216192000*x^13 - 1/83825280*x^11 + 23/12700800*x^9 - 1/6300*x^7 + 19/2520*x^5 - 17/105*x^3 + x)/(1/210*x^2 + 1) + (17, 2): ([1, -17 / 105, 19 / 2520, -1 / 6300, 23 / 12700800, -1 / 83825280, 1 / 24216192000], [1, 1 / 210]), + # k=3 : p/q = (-911/250637587200*x^11 + 3799/3797539200*x^9 - 89/753480*x^7 + 2503/376740*x^5 - 151/966*x^3 + x)/(3/83720*x^4 + 5/483*x^2 + 1) + (17, 3): ( + [1, -151 / 966, 2503 / 376740, -89 / 753480, 3799 / 3797539200, -911 / 250637587200], + [1, 5 / 483, 3 / 83720], + ), + # k=4 : p/q = (1768969/4763930371200*x^9 - 36317/472612140*x^7 + 80231/14321580*x^5 - 8234/55083*x^3 + x)/(911/1890448560*x^6 + 3799/28643160*x^4 + 631/36722*x^2 + 1) + (17, 4): ( + [1, -8234 / 55083, 80231 / 14321580, -36317 / 472612140, 1768969 / 4763930371200], + [1, 631 / 36722, 3799 / 28643160, 911 / 1890448560], + ), + # k=5 : p/q = (-62077121/1727021696400*x^7 + 9713777/2242885320*x^5 - 2020961/14377470*x^3 + x)/(1768969/124345562140800*x^8 + 36317/12335869260*x^6 + 26015/74762844*x^4 + 187642/7188735*x^2 + 1) + (17, 5): ( + [1, -2020961 / 14377470, 9713777 / 2242885320, -62077121 / 1727021696400], + [1, 187642 / 7188735, 26015 / 74762844, 36317 / 12335869260, 1768969 / 124345562140800], + ), + # k=6 : p/q = (1074305779/407195104680*x^5 - 4749115/37288929*x^3 + x)/(62077121/45149793206918400*x^10 + 9713777/58636095073920*x^8 + 5513233/407195104680*x^6 + 3873323/4524390052*x^4 + 2931413/74577858*x^2 + 1) + # k=7 : p/q = (-286685/2828954*x^3 + x)/(1074305779/924837658512768000*x^12 + 135689/2419774093440*x^10 + 210431/95052854400*x^8 + 426523/5346723060*x^6 + 1300789/509211720*x^4 + 277211/4243431*x^2 + 1) + }[variant] + + p = fast_polynomial(ctx, x * x, P, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme][1]) * x + q = fast_polynomial(ctx, x * x, Q, reverse=False, scheme=[None, horner_scheme, estrin_dac_scheme][1]) + return p / q def sine_dw(ctx, x, y): @@ -907,3 +1791,37 @@ def cosine_dw(ctx, x, y): hz = half * z w = one - hz return w + (((one - w) - hz) + ((z * r) - (x * y))) + + +def sine_cosine_kernel(ctx, r, t): + import numpy + + if isinstance(r, (numpy.float64, numpy.float32, numpy.float16)): + return sine_cosine_kernel_impl(ctx, type(r), r, t) + + largest = get_largest(ctx, r) + fp64_sn, fp64_cs = sine_cosine_kernel_impl(ctx, numpy.float64, r, t) + fp32_sn, fp32_cs = sine_cosine_kernel_impl(ctx, numpy.float32, r, t) + fp16_sn, fp16_cs = sine_cosine_kernel_impl(ctx, numpy.float16, r, t) + sn = ctx.select(largest > 1e308, fp64_sn, ctx.select(largest > 1e38, fp32_sn, fp16_sn)) + cs = ctx.select(largest > 1e308, fp64_cs, ctx.select(largest > 1e38, fp32_cs, fp16_cs)) + return sn, cs + + +def sine_cosine_kernel_impl(ctx, dtype, r, t): + import functional_algorithms as fa + import numpy + + order = {numpy.float16: 9, numpy.float32: 13, numpy.float64: 19}[dtype] + # order = {numpy.float16: 7, numpy.float32: 9, numpy.float64: 15}[dtype] + x = ctx.series(r, t) + with ctx.parameters(series_uses_dekker=True, series_uses_2sum=True, type=fa.Type.fromobject(ctx, dtype)): + sn = sine_taylor_dekker(ctx, x, order=order) + cs = cosine_taylor_dekker(ctx, x, order=order) + return sn, cs + + +def sine(ctx, x): + k, r, t = argument_reduction_trigonometric(ctx, x) + sn, cs = sine_cosine_kernel(ctx, r, t) + return ctx.select(k == 0, sn, ctx.select(k == 1, cs, ctx.select(k == 2, -sn, -cs))) diff --git a/functional_algorithms/rewrite.py b/functional_algorithms/rewrite.py index a05f5af..2305a3a 100644 --- a/functional_algorithms/rewrite.py +++ b/functional_algorithms/rewrite.py @@ -2,7 +2,7 @@ import numpy from collections import defaultdict from . import expr as _expr -from .utils import number_types, value_types, float_types, complex_types, boolean_types +from .utils import number_types, value_types, float_types, complex_types, boolean_types, warn_once class Printer: @@ -382,8 +382,9 @@ def op_unflatten(operands, kind): class Rewriter: - def __init__(self): + def __init__(self, parameters=None): self._printer = Printer() + self._parameters = parameters or {} def __call__(self, expr): result = getattr(self, expr.kind, self._notimpl)(expr) @@ -477,6 +478,8 @@ def _binary_op(self, expr, op): yvalue, ylike = y.operands if isinstance(xvalue, number_types) and isinstance(yvalue, number_types): r = op(xvalue, yvalue) + if numpy.isfinite(xvalue) and numpy.isfinite(yvalue) and not numpy.isfinite(r): + warn_once(f"{expr} evaluation resulted a non-finite value `{r}`") return expr.context.constant(r, xlike) def add(self, expr): @@ -491,6 +494,11 @@ def add(self, expr): if isinstance(value, number_types) and value == 0: return y_ + if x.kind == "series" or y.kind == "series": + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.add_series(expr.context, x, y) + def subtract(self, expr): result = self._binary_op(expr, lambda x, y: x - y) @@ -498,12 +506,18 @@ def subtract(self, expr): return result x, y = expr.operands + for x_, y_, s in [(x, y, -1), (y, x, 1)]: if x_.kind == "constant": value, like = x_.operands if isinstance(value, number_types) and value == 0: return -y_ if s == -1 else y_ + if x.kind == "series" or y.kind == "series": + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.subtract_series(expr.context, x, y) + def multiply(self, expr): result = self._binary_op(expr, lambda x, y: x * y) @@ -514,8 +528,16 @@ def multiply(self, expr): for x_, y_ in [(x, y), (y, x)]: if x_.kind == "constant": value, like = x_.operands - if isinstance(value, number_types) and value == 1: - return y_ + if isinstance(value, number_types): + if value == 1: + return y_ + if value == 0 and self._parameters.get("eliminate_zero_factors"): + return x_ + + if x.kind == "series" or y.kind == "series": + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.mul_series(expr.context, x, y) def minimum(self, expr): return self._binary_op(expr, lambda x, y: min(x, y)) @@ -527,8 +549,20 @@ def divide(self, expr): x, y = expr.operands if y.kind == "constant": value, like = y.operands - if isinstance(value, number_types) and value == 1: - return x + if isinstance(value, number_types): + if value == 1: + return x + + if x.kind == "constant": + value, like = x.operands + if isinstance(value, number_types): + if value == 0 and self._parameters.get("eliminate_zero_factors"): + return x + + if x.kind == "series" and y.kind != "series": + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.div_series(expr.context, x, y) def complex(self, expr): pass @@ -576,12 +610,12 @@ def constant(self, expr): def upcast(self, expr): (x,) = expr.operands - if x.kind == "downcast": + if x.kind == "downcast" and self._parameters.get("optimize_cast", True): return x.operands[0] def downcast(self, expr): (x,) = expr.operands - if x.kind == "upcast": + if x.kind == "upcast" and self._parameters.get("optimize_cast", True): return x.operands[0] def log(self, expr): @@ -653,6 +687,9 @@ def negative(self, expr): if x.kind == "negative": return x.operands[0] + if x.kind == "series": + return _expr.make_series(expr.context, *x.operands[0], tuple(-x_ for x_ in x.operands[1:])) + def conjugate(self, expr): (x,) = expr.operands @@ -671,6 +708,9 @@ def conjugate(self, expr): if x.kind == "conjugate": return x + if x.kind == "series": + return _expr.make_series(expr.context, *x.operands[0], tuple(expr.context.conjugate(x_) for x_ in x.operands[1:])) + def real(self, expr): (x,) = expr.operands @@ -681,6 +721,9 @@ def real(self, expr): if x.kind == "complex": return x.operands[0] + if x.kind == "series": + return _expr.make_series(expr.context, *x.operands[0], tuple(expr.context.real(x_) for x_ in x.operands[1:])) + def imag(self, expr): (x,) = expr.operands @@ -691,6 +734,9 @@ def imag(self, expr): if x.kind == "complex": return x.operands[1] + if x.kind == "series": + return _expr.make_series(expr.context, *x.operands[0], tuple(expr.context.imag(x_) for x_ in x.operands[1:])) + def _compare(self, expr, relop, relop_index, swap_relop_index): x, y = expr.operands if x.kind == "constant": @@ -810,6 +856,18 @@ def square(self, expr): if isinstance(value, number_types): return self._eval(like, "square", value) + if x.kind == "series": + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.mul_series(expr.context, x, x) + + def pow(self, expr): + base, exp = expr.operands + if base.kind == "series" and exp.kind == "constant" and isinstance(exp.operands[0], int) and exp.operands[0] >= 0: + import functional_algorithms.floating_point_algorithms as fpa + + return fpa.fast_exponent_by_squaring(expr.context, base, exp.operands[0]) + def symbol(self, expr): pass @@ -819,11 +877,26 @@ def hypot(self, expr): def is_finite(self, expr): pass + def series(self, expr): + pass + + def fma(self, expr): + pass + + def truncate(self, expr): + pass + + def remainder(self, expr): + pass + + def round(self, expr): + pass + -def rewrite(expr): +def rewrite(expr, parameters=None): """Return rewritten expression, otherwise return None.""" - rewriter = Rewriter() + rewriter = Rewriter(parameters=parameters) last_result = None result = expr @@ -842,6 +915,16 @@ def __rewrite_modifier__(expr): return expr if result is None else result +class RewriteWithParameters: + + def __init__(self, **parameters): + self._parameters = parameters + + def __rewrite_modifier__(self, expr): + result = rewrite(expr, self._parameters) + return expr if result is None else result + + class RewriteContext: """Caches rewrite results.""" @@ -908,3 +991,40 @@ def __rewrite_modifier__(self, expr): else: raise NotImplementedError(f"{type(replacement)=}") return expr + + +class ReplaceSeries: + + def __rewrite_modifier__(self, expr): + if expr.kind == "series": + from functional_algorithms import floating_point_algorithms as fpa + + index, sexp = expr.operands[0] + S = expr.context.constant(2 ** (-sexp), expr) + if sexp == 0: + return sum(reversed(expr.operands[1:-1]), expr.operands[-1]) + return fpa.fast_polynomial(expr.context, S, expr.operands[1:], reverse=False, scheme=[None, fpa.horner_scheme][1]) + return expr + + +class ReplaceFma: + + def __init__(self, backend="native"): + assert backend in {"native", "upcast", "mul_add", None}, backend + self.backend = backend + + def __rewrite_modifier__(self, expr): + if expr.kind == "fma": + from functional_algorithms import floating_point_algorithms as fpa + + if self.backend == "upcast": + return fpa.fma_upcast(expr.context, *expr.operands) + elif self.backend == "native": + return fpa.fma_native(expr.context, *expr.operands) + elif self.backend == "mul_add": + return fpa.mul_add(expr.context, *expr.operands) + elif self.backend is None: + pass # skip fma replace + else: + raise NotImplementedError(f"replace fma using backend={self.backend}") + return expr diff --git a/functional_algorithms/targets/base.py b/functional_algorithms/targets/base.py index a631c3a..fc326a6 100644 --- a/functional_algorithms/targets/base.py +++ b/functional_algorithms/targets/base.py @@ -4,7 +4,7 @@ def modifier_base(target, expr): - if expr.kind in {"symbol", "constant", "apply"}: + if expr.kind in {"symbol", "constant", "apply", "series"}: pass elif target.kind_to_target.get(expr.kind, NotImplemented) is NotImplemented: ctx = expr.context diff --git a/functional_algorithms/targets/numpy.py b/functional_algorithms/targets/numpy.py index 8ced5b8..c3428ca 100644 --- a/functional_algorithms/targets/numpy.py +++ b/functional_algorithms/targets/numpy.py @@ -66,6 +66,15 @@ def downcast_func(target, expr): return f"{t_new}({s})" +def fma_func(target, expr): + assert expr.kind == "fma", expr.kind + (x, y, z) = expr.operands + xs = target.tostring(x) + ys = target.tostring(y) + zs = target.tostring(z) + return f"(({xs}) * ({ys}) + ({zs}))" + + trace_arguments = dict( absolute=[(":complex128",), (":complex64",)], asin_acos_kernel=[(":complex128",), (":complex64",)], @@ -116,7 +125,7 @@ def make_comment(message): subtract="({0}) - ({1})", multiply="({0}) * ({1})", divide="({0}) / ({1})", - remainder="({0}) %% ({1})", + remainder="({0}) % ({1})", floor_divide="({0}) // ({1})", pow="({0}) ** ({1})", logical_and="({0}) and ({1})", @@ -154,7 +163,7 @@ def make_comment(message): ceil="numpy.ceil({0})", floor="numpy.floor({0})", copysign="numpy.copysign({0}, {1})", - round=NotImplemented, + round="numpy.round({0})", sign="numpy.sign({0})", truncate="numpy.trunc({0})", conjugate="({0}).conjugate()", @@ -175,6 +184,7 @@ def make_comment(message): upcast=upcast_func, downcast=downcast_func, is_finite="numpy.isfinite({0})", + fma=fma_func, ) constant_to_target = dict( @@ -194,6 +204,7 @@ def make_comment(message): integer32="numpy.int32", integer64="numpy.int64", integer="numpy.int64", + float16="numpy.float16", float32="numpy.float32", float64="numpy.float64", float="numpy.float64", @@ -217,7 +228,7 @@ def as_function(graph, debug=0, numpy=numpy): warnings=warnings, ) np = graph.tostring(this_module, debug=debug) - if debug >= 2: + if debug >= 1.5: print(np) exec(np, d) return d[graph.operands[0].operands[0]] @@ -272,3 +283,25 @@ def make_apply(self, expr, name, tab=""): lines.append(f"{tab} assert result.dtype == {body_type}, (result.dtype,)") lines.append(f"{tab} return result") return utils.format_python("\n".join(lines)) + + +def jit(**params): + + import functional_algorithms as fa + + rewrite_parameters = params.get("rewrite_parameters", {}) + + def jit_decor(func): + assert "parameters" not in params # use `with ctx.parameters(...)` instead + ctx = fa.Context(paths=params.get("paths"), parameters=params.get("parameters")) + dtype = params.get("dtype", numpy.float32) + graph = ctx.trace(func, dtype) + graph2 = graph.rewrite( + fa.rewrite.ReplaceSeries(), + fa.rewrite.ReplaceFma(backend=rewrite_parameters.get("fma_backend", "native")), + this_module, + fa.rewrite.RewriteWithParameters(**rewrite_parameters), + ) + return as_function(graph2, debug=params.get("debug", 0)) + + return jit_decor diff --git a/functional_algorithms/tests/test_expr.py b/functional_algorithms/tests/test_expr.py index 77f2214..973952f 100644 --- a/functional_algorithms/tests/test_expr.py +++ b/functional_algorithms/tests/test_expr.py @@ -749,3 +749,72 @@ def test_logical_op_collect(): assert_equal( fa.rewrite.op_collect((x & z) | (y & z) | (x & z), over_commutative=True, over_idempotent=True, **kwargs), (x | y) & z ) + + +def test_series(): + + ctx = fa.Context() + + x = ctx.symbol("x") + y = ctx.symbol("y") + z = ctx.symbol("z") + w = ctx.symbol("w") + + s1 = ctx.series(x, y, unit_index=0) + s2 = ctx.series(z, w, unit_index=0) + s3 = ctx.series(z, w, unit_index=1) + s4 = ctx.series(z, w, unit_index=-1) + s5 = ctx.series(z, w, unit_index=-3) + + def rewrite(expr): + return expr.rewrite(fa.rewrite) + + assert_equal(s1 + s2, ctx.add(s1, s2)) + assert_equal(rewrite(s1 + s2), ctx.series(x + z, y + w, unit_index=0)) + assert_equal(rewrite(s1 + s3), ctx.series(z, x + w, y, unit_index=1)) + assert_equal(rewrite(s3 + s1), ctx.series(z, w + x, y, unit_index=1)) + assert_equal(rewrite(s1 + s4), ctx.series(x, y + z, w, unit_index=0)) + assert_equal(rewrite(s4 + s1), ctx.series(x, z + y, w, unit_index=0)) + assert_equal(rewrite(s1 + s5), ctx.series(x, y, 0, z, w, unit_index=0)) + assert_equal(rewrite(s5 + s1), ctx.series(x, y, 0, z, w, unit_index=0)) + assert_equal(rewrite(s4 + s5), ctx.series(z, w, z, w, unit_index=-1)) + + assert_equal(s1 - s2, ctx.subtract(s1, s2)) + assert_equal(rewrite(s1 - s2), ctx.series(x - z, y - w, unit_index=0)) + assert_equal(rewrite(s1 - s3), ctx.series(-z, x - w, y, unit_index=1)) + assert_equal(rewrite(s3 - s1), ctx.series(z, w - x, -y, unit_index=1)) + assert_equal(rewrite(s1 - s4), ctx.series(x, y - z, -w, unit_index=0)) + assert_equal(rewrite(s4 - s1), ctx.series(-x, z - y, w, unit_index=0)) + assert_equal(rewrite(s1 - s5), ctx.series(x, y, 0, -z, -w, unit_index=0)) + assert_equal(rewrite(s5 - s1), ctx.series(-x, -y, 0, z, w, unit_index=0)) + assert_equal(rewrite(s4 - s5), ctx.series(z, w, -z, -w, unit_index=-1)) + assert_equal(rewrite(s5 - s4), ctx.series(-z, -w, z, w, unit_index=-1)) + + assert_equal(rewrite(s1 + z), ctx.series(x + z, y, unit_index=0)) + assert_equal(rewrite(s1 - z), ctx.series(x - z, y, unit_index=0)) + assert_equal(rewrite(z + s1), ctx.series(z + x, y, unit_index=0)) + assert_equal(rewrite(z - s1), ctx.series(z - x, -y, unit_index=0)) + assert_equal(rewrite(s2 + x), ctx.series(z + x, w, unit_index=0)) + assert_equal(rewrite(s3 + x), ctx.series(z, w + x, unit_index=1)) + assert_equal(rewrite(s4 + x), ctx.series(x, z, w, unit_index=0)) + assert_equal(rewrite(s5 + x), ctx.series(x, 0, 0, z, w, unit_index=0)) + + assert_equal(s1 * s2, ctx.multiply(s1, s2)) + assert_equal(rewrite(s1 * s2), ctx.series(x * z, x * w + y * z, y * w, unit_index=0)) + assert_equal(rewrite(s2 * s2), ctx.series(z * z, z * w + w * z, w * w, unit_index=0)) + assert_equal(rewrite(s3 * s3), ctx.series(z * z, z * w + w * z, w * w, unit_index=2)) + assert_equal(rewrite(s4 * s4), ctx.series(z * z, z * w + w * z, w * w, unit_index=-2)) + assert_equal(rewrite(s4 * s5), ctx.series(z * z, z * w + w * z, w * w, unit_index=-4)) + + assert_equal(rewrite(s3**2), ctx.series(z * z, z * w + w * z, w * w, unit_index=2)) + + assert_equal(rewrite(s1 * z), ctx.series(x * z, y * z, unit_index=0)) + assert_equal(rewrite(z * s1), ctx.series(z * x, z * y, unit_index=0)) + assert_equal(rewrite(s2 * x), ctx.series(z * x, w * x, unit_index=0)) + assert_equal(rewrite(s3 * x), ctx.series(z * x, w * x, unit_index=1)) + assert_equal(rewrite(s5 * x), ctx.series(z * x, w * x, unit_index=-3)) + + assert_equal(rewrite(s1 / z), ctx.series(x / z, y / z, unit_index=0)) + + assert_equal(rewrite(-s1), ctx.series(-x, -y, unit_index=0)) + assert_equal(rewrite(-s3), ctx.series(-z, -w, unit_index=1)) diff --git a/functional_algorithms/tests/test_floating_point_algorithms.py b/functional_algorithms/tests/test_floating_point_algorithms.py index 8c14978..da09722 100644 --- a/functional_algorithms/tests/test_floating_point_algorithms.py +++ b/functional_algorithms/tests/test_floating_point_algorithms.py @@ -23,6 +23,23 @@ def binary_op(request): NumpyContext = utils.NumpyContext +def show_ulp(ulp, title=None): + rest = 0 + u5 = None + if ulp and title is not None: + print(f"{title}:") + for i, u in enumerate(sorted(ulp)): + if i < 5: + print(f" ULP difference {u}: {ulp[u]}") + else: + if u5 is None: + u5 = u + rest += ulp[u] + else: + if rest: + print(f" ULP difference >= {u5}: {rest}") + + def test_split_veltkamp(dtype): ctx = NumpyContext() p = utils.get_precision(dtype) @@ -74,6 +91,25 @@ def test_split_veltkamp(dtype): assert len(bl) < (p + 1) // 2 +def test_split_veltkamp2(dtype): + fi = numpy.finfo(dtype) + ctx = NumpyContext() + p = utils.get_precision(dtype) + C = utils.get_veltkamp_splitter_constant(dtype) + largest = fpa.get_largest(ctx, dtype(0)) + + max_x = largest + min_x = fi.smallest_normal * (C + C - dtype(2)) + size = 1000 + for x in utils.real_samples(size, dtype=dtype, min_value=min_x, max_value=max_x): + xh, xl = fpa.split_veltkamp2(ctx, x) + assert x == xh + xl + xh + + x = -x + xh, xl = fpa.split_veltkamp2(ctx, x) + assert x == xh + xl + xh + + def test_mul_dekker(dtype): import mpmath @@ -105,10 +141,8 @@ def test_mul_dekker(dtype): for x in utils.real_samples(size, dtype=dtype, min_value=min_x, max_value=max_x): x_mp = utils.float2mpf(ctx, x) for y in utils.real_samples(size, dtype=dtype, min_value=min_x, max_value=max_x): - xy = x * y xyh, xyl = fpa.mul_dekker(None, x, y, C) assert numpy.isfinite(xyl) - assert xyh == xy y_mp = utils.float2mpf(ctx, y) xyh_mp = utils.float2mpf(ctx, xyh) xyl_mp = utils.float2mpf(ctx, xyl) @@ -122,7 +156,7 @@ def test_mul_dekker(dtype): ex = utils.mpf2float(dtype, expected) u = utils.diff_ulp(xyh + xyl, ex) ulp_counts[u] += 1 - ulp_counts_native[utils.diff_ulp(xy, ex)] += 1 + ulp_counts_native[utils.diff_ulp(x * y, ex)] += 1 assert u <= max_valid_ulp_count print(f"\nULP counts using mul_dekker: {dict(ulp_counts)}\nULP counts using x*y: {dict(ulp_counts_native)}") @@ -668,6 +702,7 @@ def test_argument_reduction_trigonometric(dtype): ctx = NumpyContext() fi = numpy.finfo(dtype) min_value = fi.smallest_normal + min_value = dtype(0.5) # argument reduction is used only for value larger that pi / 4 max_value = fi.max largest = fpa.get_largest(ctx, dtype(0)) @@ -675,56 +710,666 @@ def test_argument_reduction_trigonometric(dtype): max_prec = {numpy.float16: 24, numpy.float32: 149, numpy.float64: 1074}[dtype] - if dtype == numpy.float64: - x = numpy.ldexp(6381956970095103, 797) - k, r, t = fpa.argument_reduction_trigonometric(ctx, x) # 4.687165924254629e-19 - # ulp difference from dtype(4.687165924254624e-19) is 5. Is - # the reference value from - # https://userpages.cs.umbc.edu/phatak/645/supl/Ng-ArgReduction.pdf - # wrong? - u = utils.diff_ulp(r + t, dtype(4.687165924254624e-19)) - assert u <= 5, (r, t, r + t) - size = 1000 samples = utils.real_samples(size, dtype=dtype, min_value=min_value, max_value=max_x) ulp_counts = defaultdict(int) - for x in samples: - assert isinstance(x, dtype) - k, r, t = fpa.argument_reduction_trigonometric(ctx, x) + mp_ctx = mpmath.mp + with mp_ctx.workprec(max_prec): + # multiprecision value of 2 / pi and pi / 2 + two_over_pi_mp = 2 / mp_ctx.pi + pi_over_two_mp = mp_ctx.pi / 2 + + # multiword represention of 2 / pi + two_over_pi_max_length = {numpy.float16: 4, numpy.float32: 11, numpy.float64: 39}.get(dtype, None) + two_over_pi_mw = utils.get_two_over_pi_multiword(dtype, max_length=two_over_pi_max_length) + print(f"{two_over_pi_mw=}") + two_over_pi_mw_mp = None + for v in reversed(two_over_pi_mw): + if two_over_pi_max_length is None: + assert abs(fpa.split_veltkamp(ctx, v)[1]) == 0 + elif two_over_pi_mw_mp is not None: + assert abs(fpa.split_veltkamp(ctx, v)[1]) == 0 + v_mp = utils.float2mpf(mp_ctx, v) + if two_over_pi_mw_mp is None: + two_over_pi_mw_mp = v_mp + else: + two_over_pi_mw_mp += v_mp + + if two_over_pi_max_length is None: + assert two_over_pi_mw_mp == two_over_pi_mp + + # pi / 2 = pi2h + pi2l + pi2h = utils.mpf2float(dtype, pi_over_two_mp) + pi2l = utils.mpf2float(dtype, pi_over_two_mp - utils.float2mpf(mp_ctx, pi2h)) + + ulp_stage1 = defaultdict(int) + ulp_stage2 = defaultdict(int) + four = dtype(4) + two = dtype(2) + zero = dtype(0) + cumerr = defaultdict(dtype) + for x in samples: + x_mp = utils.float2mpf(mp_ctx, x) - assert k in [0, 1, 2, 3], x - assert abs(r) <= dtype(numpy.pi / 4) * 1.1, (r, k, x) - assert isinstance(r, dtype) + # multiprecision value of x * (2 / pi) + with mp_ctx.workprec(max_prec * 2): + x2pi_mp = x_mp * two_over_pi_mp + x2pi_mp_m4 = x2pi_mp - mp_ctx.floor((x2pi_mp + 2) / 4) * 4 + assert abs(x2pi_mp_m4) <= 2 + + # split x into xh + xl + xh, valid for any x larger than 1/2 + xh, xl = fpa.split_veltkamp2(ctx, x) + assert xh + xl + xh == x + assert fpa.split_veltkamp(ctx, xh)[1] == 0 + assert fpa.split_veltkamp(ctx, xl)[1] == 0 + + # multiword representation of x * (2 / pi) + r_mw_h = [v * xh for v in two_over_pi_mw] + r_mw_l = [v * xl for v in two_over_pi_mw] + + """Next. we'll reduce x * (2 / pi) by subtracting 4 * N, N is integer. + + There exists several ways to reduce a value by 4 * N that + involve using functions like truncate, round, floor, ceil, + remainder, fmod, rint, %, etc. + + As a result of the following tests, the cumulative error + of these approches is as follows: + + float16: + fmod : 4.172325134277344e-06 + rint : 4.172325134277344e-06 + round : 4.172325134277344e-06 + truncate : 4.172325134277344e-06 + ceil : 0.4892578125 + % : 0.53466796875 + floor : 0.53466796875 + remainder : 0.53466796875 + + float32: + fmod : 3.2229864679470793e-44 + rint : 3.2229864679470793e-44 + round : 3.2229864679470793e-44 + truncate : 3.2229864679470793e-44 + ceil : 6.776367808924988e-05 + % : 7.783176988596097e-05 + floor : 7.783176988596097e-05 + remainder : 7.783176988596097e-05 + + float64: + fmod : 2.5e-323 + rint : 2.5e-323 + round : 2.5e-323 + truncate : 2.5e-323 + ceil : 1.20780455651524e-13 + % : 1.3584433071495718e-13 + floor : 1.3584433071495718e-13 + remainder : 1.3584433071495718e-13 + + StableHLO provides the following functions: ceil, floor, + remainder, round_nearest_afz, round_nearest_even. + + In the following, we'll use round-nearest-even approach for reducing by 4*N. + """ + if 0: + # (2 * xh) - truncate((2 * xh) / 4) * 4 = (xh - truncate(xh / 2) * 2) * 2 + r_mw_h_m4_t = [v - ctx.truncate(v / two) * two for v in r_mw_h] + r_mw_l_m4_t = [v - ctx.truncate(v / four) * four for v in r_mw_l] + + r_mw_h_m4_r = [v - ctx.round(v / two) * two for v in r_mw_h] + r_mw_l_m4_r = [v - ctx.round(v / four) * four for v in r_mw_l] + + r_mw_h_m4_f = [v - ctx.floor(v / two) * two for v in r_mw_h] + r_mw_l_m4_f = [v - ctx.floor(v / four) * four for v in r_mw_l] + + r_mw_h_m4_c = [v - ctx.ceil(v / two) * two for v in r_mw_h] + r_mw_l_m4_c = [v - ctx.ceil(v / four) * four for v in r_mw_l] + + r_mw_h_m4_rem = [ctx.remainder(v, two) for v in r_mw_h] + r_mw_l_m4_rem = [ctx.remainder(v, four) for v in r_mw_l] + + r_mw_h_m4_mod = [v % two for v in r_mw_h] + r_mw_l_m4_mod = [v % four for v in r_mw_l] + + r_mw_h_m4_fm = [ctx.fmod(v, two) for v in r_mw_h] + r_mw_l_m4_fm = [ctx.fmod(v, four) for v in r_mw_l] + + r_mw_h_m4_rint = [v - ctx.rint(v / two) * two for v in r_mw_h] + r_mw_l_m4_rint = [v - ctx.rint(v / four) * four for v in r_mw_l] + + def mp_m4(v): + if v >= 4 or v < 0: + r = v - mp_ctx.floor(v / 4) * 4 + else: + r = v + assert r >= 0 + assert r < 4 + return r + + with mp_ctx.workprec(max_prec * 2): + r_mw_mp = utils.multiword2mpf(mp_ctx, r_mw_h) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l) + r_mw_mp_m4_t = utils.multiword2mpf(mp_ctx, r_mw_h_m4_t) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_t) + r_mw_mp_m4_r = utils.multiword2mpf(mp_ctx, r_mw_h_m4_r) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_r) + r_mw_mp_m4_mod = utils.multiword2mpf(mp_ctx, r_mw_h_m4_mod) * 2 + utils.multiword2mpf( + mp_ctx, r_mw_l_m4_mod + ) + r_mw_mp_m4_f = utils.multiword2mpf(mp_ctx, r_mw_h_m4_f) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_f) + r_mw_mp_m4_c = utils.multiword2mpf(mp_ctx, r_mw_h_m4_c) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_c) + r_mw_mp_m4_rem = utils.multiword2mpf(mp_ctx, r_mw_h_m4_rem) * 2 + utils.multiword2mpf( + mp_ctx, r_mw_l_m4_rem + ) + r_mw_mp_m4_fm = utils.multiword2mpf(mp_ctx, r_mw_h_m4_fm) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_fm) + r_mw_mp_m4_rint = utils.multiword2mpf(mp_ctx, r_mw_h_m4_rint) * 2 + utils.multiword2mpf( + mp_ctx, r_mw_l_m4_rint + ) - mp_ctx = mpmath.mp - with mp_ctx.workprec(max_prec * 10): - x_mp = utils.float2mpf(mp_ctx, x) - y_mp = x_mp * (2 / mp_ctx.pi) - Nk = mp_ctx.floor(y_mp) + r_mw_mp_m4_t = mp_m4(r_mw_mp_m4_t) + r_mw_mp_m4_r = mp_m4(r_mw_mp_m4_r) + r_mw_mp_m4_mod = mp_m4(r_mw_mp_m4_mod) + r_mw_mp_m4_f = mp_m4(r_mw_mp_m4_f) + r_mw_mp_m4_c = mp_m4(r_mw_mp_m4_c) + r_mw_mp_m4_rem = mp_m4(r_mw_mp_m4_rem) + r_mw_mp_m4_fm = mp_m4(r_mw_mp_m4_fm) + r_mw_mp_m4_rint = mp_m4(r_mw_mp_m4_rint) + + assert utils.mpf2float(dtype, x2pi_mp) == utils.mpf2float(dtype, r_mw_mp) + + cumerr["truncate"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_t - x2pi_mp_m4)) + cumerr["round"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_r - x2pi_mp_m4)) + cumerr["%"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_mod - x2pi_mp_m4)) + cumerr["floor"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_f - x2pi_mp_m4)) + cumerr["ceil"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_c - x2pi_mp_m4)) + cumerr["remainder"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_rem - x2pi_mp_m4)) + cumerr["fmod"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_fm - x2pi_mp_m4)) + cumerr["rint"] += utils.mpf2float(dtype, abs(r_mw_mp_m4_rint - x2pi_mp_m4)) + + r_mw_h_m4_r = [(v - ctx.round(v / two) * two) for v in r_mw_h] + r_mw_l_m4_r = [v - ctx.round(v / four) * four for v in r_mw_l] + with mp_ctx.workprec(max_prec * 2): + r_mw_mp_m4_r = utils.multiword2mpf(mp_ctx, r_mw_h_m4_r) * 2 + utils.multiword2mpf(mp_ctx, r_mw_l_m4_r) + r_mw_mp_m4_r = r_mw_mp_m4_r - mp_ctx.floor(r_mw_mp_m4_r / 4) * 4 + + if two_over_pi_max_length is None: + assert utils.mpf2float(dtype, r_mw_mp_m4_r) == utils.mpf2float(dtype, x2pi_mp_m4) + + y = None + t = None + for zh, zl in zip(reversed(r_mw_h_m4_r), reversed(r_mw_l_m4_r)): + if y is None: + y, t = fpa.add_2sum(ctx, zh + zh, zl) + else: + y, th = fpa.add_2sum(ctx, y, zh + zh) + y, tl = fpa.add_2sum(ctx, y, zl) + t += th + tl + + # compute `(y + t) - round((y + t) / 4) * 4 -> y' + t` + # such that -2.0 <= y' + t <= 2.0 + n1 = ctx.round(y / four) * four + y1 = y - n1 + y = ctx.select(y1 + two < -t, y - (n1 - four), ctx.select(y1 - two > -t, y - (n1 + four), y1)) + assert abs(y + t) <= two, (x, y, t) + + if 1: + y2, t2 = fpa.argument_reduction_trigonometric_stage1_impl(ctx, dtype, x) + assert y2 == y + assert t2 == t + + with mp_ctx.workprec(max_prec * 2): + y_mp = utils.float2mpf(mp_ctx, y) + utils.float2mpf(mp_ctx, t) + + u = utils.diff_ulp(utils.mpf2float(dtype, y_mp), utils.mpf2float(dtype, x2pi_mp_m4)) + ulp_stage1[u] += 1 + if u > 0: + print(f"1: {x=} {y, t=}") + print( + f"diff(result={str(utils.mpf2float(dtype, y_mp))}, expected={str(utils.mpf2float(dtype, x2pi_mp_m4))}) -> {u}" + ) + + k = ctx.round(y) + yk = y - k + + if 1: + assert k in [-2, -1, 0, 1, 2], (y, k, y - k, t, (y2, t2)) + + """ + (yk + t) * (pi2h + pi2l) = yk * pi2h + yk * pi2l + t * pi2h + t * pi2l + """ + r1h, r1l = fpa.mul_dekker(ctx, yk, pi2h) + r2h, r2l = fpa.mul_dekker(ctx, yk, pi2l) + r3h, r3l = fpa.mul_dekker(ctx, t, pi2h) + r4 = t * pi2l + + r, rrl1 = fpa.add_2sum(ctx, r1h, r2h, fast=True) + r, rrl2 = fpa.add_2sum(ctx, r, r3h, fast=True) + r, rrl3 = fpa.add_2sum(ctx, r, r4, fast=True) + s = rrl3 + r3l + rrl2 + r2l + rrl1 + r1l + + if 1: + k2, r2, s2 = fpa.argument_reduction_trigonometric_stage2_impl(ctx, dtype, y, t) + + assert k == k2, ((k, r, s), (k2, r2, s2)) + assert r == r2 + assert s == s2 + + with mp_ctx.workprec(max_prec * 2): + if 0: + rx_mp = ( + utils.float2mpf(mp_ctx, k) * pi_over_two_mp + + (utils.float2mpf(mp_ctx, y - k) + utils.float2mpf(mp_ctx, t)) * pi_over_two_mp + ) + else: + rx_mp = ( + utils.float2mpf(mp_ctx, r) + utils.float2mpf(mp_ctx, s) + utils.float2mpf(mp_ctx, k) * pi_over_two_mp + ) + rx_mp_mp = x2pi_mp_m4 * pi_over_two_mp + + rrrt_mp = utils.float2mpf(mp_ctx, r) + utils.float2mpf(mp_ctx, s) + ub = utils.mpf2float(dtype, pi_over_two_mp / 2) + for i in range(5): + ub = numpy.nextafter(ub, dtype(1000)) + assert utils.mpf2float(dtype, abs(rrrt_mp)) <= ub + + u = utils.diff_ulp(utils.mpf2float(dtype, rx_mp), utils.mpf2float(dtype, rx_mp_mp)) + ulp_stage2[u] += 1 + if u > 0: + print(f"2: {x=} {y, t=} {k, r, s=} {u=}") + print(f"{rrl3, r3l, rrl2, r2l, rrl1, r1l=}") + show_ulp(ulp_stage1, title="Stage1[x * (2 / pi) mod 4 -> y + t]") + show_ulp(ulp_stage2, title="Stage2[(y + t) * (pi / 2) -> k * pi / 2 + r + s]") + + for e, m in sorted((e, m) for (m, e) in cumerr.items()): + print(f"{m:10}: {e}") + + +def test_sine_pade(dtype): + import mpmath + from collections import defaultdict + + t_prec = utils.get_precision(dtype) + working_prec = {11: 50 * 2, 24: 50 * 2, 53: 74 * 2}[t_prec] + ctx = NumpyContext() + size = 10_000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + size = len(samples) + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + + for variant in [ + (11, 2), + (11, 3), + (11, 4), + (11, 5), + (13, 2), + (13, 3), + (13, 4), + (13, 5), + (13, 6), + (17, 2), + (17, 3), + (17, 4), + (17, 5), + ]: + ulp = defaultdict(int) + for x in samples: + expected_sn = utils.mpf2float(dtype, mpctx.sin(utils.float2mpf(mpctx, x))) + sn = fpa.sine_pade(ctx, x, variant=variant) + u = utils.diff_ulp(sn, expected_sn) + ulp[u] += 1 + + print(f"{variant=}") + show_ulp(ulp) + + +@pytest.mark.parametrize( + "func,fma", [("sin", "upcast"), ("sin", "mul_add"), ("sin_dekker", "native"), ("sin", "native"), ("numpy.sin", None)] +) +def test_sine_taylor(dtype, func, fma): + import mpmath + from collections import defaultdict + + t_prec = utils.get_precision(dtype) + working_prec = {11: 50 * 4, 24: 50 * 4, 53: 74 * 16}[t_prec] + optimal_order = {11: 7, 24: 9, 53: 15}[t_prec] + size = 1000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + size = len(samples) + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + for order in [optimal_order, 1, 3, 5, 7, 9, 11, 13, 17, 19][:1]: + + if func == "sin_dekker": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + ) + def sin_dekker_func(ctx, x): + with ctx.parameters(series_uses_dekker=True, series_uses_2sum=True): + return fpa.sine_taylor_dekker(ctx, x, order=order) + + elif func == "sin": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def sin_func(ctx, x): + with ctx.parameters(series_uses_2sum=True): + return fpa.sine_taylor(ctx, x, order=order, split=False) + + ulp = defaultdict(int) + for x in samples: + expected_sn = utils.mpf2float(dtype, mpctx.sin(utils.float2mpf(mpctx, x))) + if func == "numpy.sin": + sn = numpy.sin(x) + elif func == "sin": + sn = sin_func(x) + elif func == "sin_dekker": + sn = sin_dekker_func(x) + else: + assert 0, func # not implemented + """ + sn = fpa.sine_taylor(ctx, x, order=order, split=False) + snh, snl = fpa.sine_taylor(ctx, x, order=order, split=True) + sn2 = utils.mpf2float(dtype, utils.float2mpf(mpctx, snh) + utils.float2mpf(mpctx, snl)) + assert sn == sn2 + """ + u = utils.diff_ulp(sn, expected_sn) + ulp[u] += 1 + + show_ulp(ulp) + + +def test_sine_taylor_dekker(dtype): + import mpmath + from collections import defaultdict + + t_prec = utils.get_precision(dtype) + working_prec = {11: 50 * 2, 24: 50 * 2, 53: 74 * 2}[t_prec] + optimal_order = {11: 7, 24: 9, 53: 15}[t_prec] + ctx = NumpyContext() + size = 1000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + size = len(samples) + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + for order in [optimal_order, 1, 3, 5, 7, 9, 11, 13, 17, 19][:1]: + ulp = defaultdict(int) + for x in samples: + expected_sn = utils.mpf2float(dtype, mpctx.sin(utils.float2mpf(mpctx, x))) + sn = fpa.sine_taylor_dekker(ctx, x, order=order) + if type(sn) is tuple: + sn = sum(reversed(sn[1:-1]), sn[-1]) + u = utils.diff_ulp(sn, expected_sn) + ulp[u] += 1 + + if 0: + c = "." if u == 0 else ("v" if sn < expected_sn else "^") + print(c, end="") + + show_ulp(ulp) + + +@pytest.mark.parametrize( + "func,fma", + [ + ("cos", "upcast"), + ("cos", "mul_add"), + ("cos", "native"), + ("cos_dekker", "native"), + ("cos_numpy", None), + ("cosm1_dekker", "native"), + ("cosm1", "upcast"), + ("cosm1_sin", "upcast"), + ("cosm1_sin_numpy", None), + ("cosm1_numpy", None), + ], +) +def test_cosine_taylor(dtype, fma, func): + import mpmath + from collections import defaultdict - expected_r1 = utils.mpf2float(dtype, (y_mp - Nk) * (mp_ctx.pi / 2)) - expected_k1 = utils.mpf2float(dtype, Nk % 4) + t_prec = utils.get_precision(dtype) + working_prec = {11: 50 * 4, 24: 50 * 4, 53: 74 * 16}[t_prec] + optimal_order = {11: 9, 24: 13, 53: 19}[t_prec] + size = 1000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + size = len(samples) + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + for order in [optimal_order, 1, 3, 5, 7, 9, 11, 13, 17, 19][:1]: - expected_r2 = utils.mpf2float(dtype, (y_mp - (Nk + 1)) * (mp_ctx.pi / 2)) - expected_k2 = utils.mpf2float(dtype, (Nk + 1) % 4) + if func.startswith("cosm1"): + + def f_expected(x): + return mpctx.cos(x) - 1 - u_r1 = utils.diff_ulp(r + t, expected_r1) - u_r2 = utils.diff_ulp(r + t, expected_r2) - u_r = min(u_r1, u_r2) - if u_r == u_r1: - expected_r = expected_r1 - expected_k = expected_k1 else: - expected_r = expected_r2 - expected_k = expected_k2 - ulp_counts[u_r] += 1 + def f_expected(x): + return mpctx.cos(x) + + if func in {"cos_dekker", "cosm1_dekker"}: + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(eliminate_zero_factors=True), + ) + def f(ctx, x): + with ctx.parameters(series_uses_dekker=True, series_uses_2sum=True): + return fpa.cosine_taylor_dekker(ctx, x, order=order, drop_leading_term=func.startswith("cosm1")) + + elif func == "cos": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def f(ctx, x): + return fpa.cosine_taylor(ctx, x, order=order, split=False) + + elif func == "cosm1": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def f(ctx, x): + return fpa.cosine_taylor(ctx, x, order=order, split=False, drop_leading_term=True) + + elif func == "cosm1_sin": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def f(ctx, x): + two = ctx.constant(2, x) + sn = fpa.sine_taylor(ctx, x / two, order=order, split=False) + return -two * sn * sn + + elif func == "cos_numpy": + + f = numpy.cos + + elif func == "cosm1_numpy": + + def f(x): + return numpy.cos(x) - dtype(1) + + elif func == "cosm1_sin_numpy": + + def f(x): + two = dtype(2) + sn = numpy.sin(x / two) + return -two * sn * sn - assert k == expected_k - if dtype == numpy.float16: - assert r == expected_r or u_r <= 10 else: - assert r == expected_r or u_r <= 1 + assert 0, func # not impl + + ulp = defaultdict(int) + for x in samples: + expected = utils.mpf2float(dtype, f_expected(utils.float2mpf(mpctx, x))) + cs = f(x) + u = utils.diff_ulp(cs, expected) + ulp[u] += 1 + + print() + show_ulp(ulp) + + +@pytest.mark.parametrize("func,fma", [("fast", "upcast"), ("fast", "native"), ("dekker", None), ("numpy.power", None)]) +@pytest.mark.parametrize("exponent", [2, 3, 4, 5]) +def test_fast_exponent_by_squaring(dtype, exponent, func, fma): + import mpmath + + t_prec = utils.get_precision(dtype) + + working_prec = {11: 50 * 2, 24: 50 * 2, 53: 74 * 2}[t_prec] + npctx = fa.utils.NumpyContext() + size = 1000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp - for u in sorted(ulp_counts): - print(f"ULP difference {u}: {ulp_counts[u]}") + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def fast_func(ctx, x): + return fpa.fast_exponent_by_squaring(ctx, x, exponent) + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + rewrite_parameters=dict(optimize_cast=False, fma_backend=fma), + ) + def dekker_func(ctx, x): + seq = fpa.fast_exponent_by_squaring_dekker(ctx, x, exponent) + if type(seq) is tuple: + return sum(reversed(seq[:-1]), seq[-1]) + return seq + + ulp = defaultdict(int) + for x in samples[::-1]: + x_mp = utils.float2mpf(mpctx, x) + expected = utils.mpf2float(dtype, x_mp**exponent) + + if func == "fast": + r = fast_func(x) + elif func == "dekker": + r = dekker_func(x) + elif func == "numpy.power": + r = numpy.power(x, exponent, dtype=dtype) + else: + assert 0, func # not implemented + + u = utils.diff_ulp(r, expected, flush_subnormals=True) + ulp[u] += 1 + + if 0: + c = "." if u == 0 else ("v" if r < expected else "^") + print(c, end="") + + show_ulp(ulp) + + +@pytest.mark.parametrize("backend", ["native", "upcast", "upcast2"]) +def test_fma(dtype, backend): + + if (dtype, backend) in { + (numpy.float64, "upcast2"), + (numpy.float128, "upcast"), + (numpy.float128, "upcast2"), + }: + pytest.skip(f"support not implemented") + + import mpmath + + t_prec = utils.get_precision(dtype) + working_prec = {11: 50 * 4, 24: 50 * 4, 53: 74 * 4}[t_prec] + mth = dict(native=fpa.fma_native, upcast=fpa.fma_upcast, upcast2=fpa.fma_upcast2)[backend] + npctx = NumpyContext() + size = 30 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(-1), max_value=dtype(1))) + + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + samples_mp = [utils.float2mpf(mpctx, v) for v in samples] + ulp = defaultdict(int) + for x, x_mp in zip(samples, samples_mp): + for y, y_mp in zip(samples, samples_mp): + for z, z_mp in zip(samples, samples_mp): + expected = utils.mpf2float(dtype, x_mp * y_mp + z_mp) + r = mth(npctx, x, y, z) + u = utils.diff_ulp(r, expected, flush_subnormals=True) + + ulp[u] += 1 + if 0: + c = "." if u == 0 else ("v" if r < expected else "^") + print(c, end="") + show_ulp(ulp) + + +@pytest.mark.parametrize("func", ["sine", "numpy.sin"]) +def test_sine(dtype, func): + import mpmath + from collections import defaultdict + + npctx = NumpyContext() + fi = numpy.finfo(dtype) + t_prec = utils.get_precision(dtype) + working_prec = {11: 24, 24: 50 * 4, 53: 74 * 16}[t_prec] + size = 1000 + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=dtype(numpy.pi / 4))) + samples = list(utils.real_samples(size, dtype=dtype, min_value=dtype(0), max_value=fi.max)) + size = len(samples) + with mpmath.mp.workprec(working_prec): + mpctx = mpmath.mp + + def f_expected(x): + return mpctx.sin(x) + + if func == "sine": + + @fa.targets.numpy.jit( + paths=[fpa], + dtype=dtype, + debug=(1.5 if size <= 10 else 0), + ) + def f(ctx, x): + return fpa.sine(ctx, x) + + elif func == "numpy.sin": + + f = numpy.sin + + else: + assert 0, func # not implemented + + ulp = defaultdict(int) + for x in samples: + expected = utils.mpf2float(dtype, f_expected(utils.float2mpf(mpctx, x))) + result = f(x) + u = utils.diff_ulp(result, expected) + if u > 5: + print(f"{u=} {x, result, expected=}") + ulp[u] += 1 + + print() + show_ulp(ulp) diff --git a/functional_algorithms/tests/test_utils.py b/functional_algorithms/tests/test_utils.py index 59d6530..2d5c2df 100644 --- a/functional_algorithms/tests/test_utils.py +++ b/functional_algorithms/tests/test_utils.py @@ -375,7 +375,7 @@ def test_float2mpf(real_dtype): if real_dtype != numpy.longdouble: assert utils.mpf2bin(m) == utils.float2bin(v) - if real_dtype in {numpy.float32, numpy.float64}: + if real_dtype in {numpy.float16, numpy.float32, numpy.float64}: for f in utils.real_samples(1000, dtype=real_dtype): v = real_dtype(f) m = utils.float2mpf(ctx, v) @@ -534,11 +534,14 @@ def test_mpf2multiword(real_dtype): for x in [ctx.pi + 0, ctx.log(2)]: lst = utils.mpf2multiword(dtype, x) for w in lst: - assert w > 0 + assert lst[-1] >= 0 + assert lst[-1] > 0 result = sum([utils.float2mpf(ctx, w) for w in lst], utils.float2mpf(ctx, dtype(0))) - assert result == x or abs(utils.mpf2float(dtype, result - x)) == 0 - if lst[-1] == 0: - break + d = result - x + if m < max_m: + assert result == x + else: + assert abs(utils.mpf2float(dtype, result - x)) == 0 def test_mpf2multiword_log2(real_dtype): @@ -667,3 +670,50 @@ def test_mpf2multiword_log2(real_dtype): stats["redundant"] += 1 break assert stats["non_redundant"] > 0 + + +def test_float2fraction(real_dtype): + import mpmath + + if real_dtype == numpy.longdouble: + pytest.skip(f"support not implemented") + + for x in utils.real_samples(10_000, dtype=real_dtype, include_subnormal=True): + q = utils.float2fraction(x) + r = utils.fraction2float(real_dtype, q) + assert x == r + + +def test_heron_10005(): + import mpmath + + x = 10005 + + for niter in range(1, 8): + q = utils.heron(x, niter=niter) + num, denom = q.numerator, q.denominator + last_prec_with_zero_err = 0 + for prec in range(10, 2000): + with mpmath.workprec(prec): + ctx = mpmath.mp + expected = ctx.sqrt(x) + result = ctx.mpf(num) / denom + if result - expected == 0: + last_prec_with_zero_err = prec + # print(niter, last_prec_with_zero_err, q) + + +def test_pi2fraction(): + import mpmath + + for n in range(2, 10): + for niter in range(2, 5): + q = utils.pi2fraction(n, niter=niter) + num, denom = q.numerator, q.denominator + last_prec_with_zero_err = 0 + for prec in range(10, 2000): + with mpmath.workprec(prec): + ctx = mpmath.mp + result = ctx.mpf(num) / denom + if result - ctx.pi == 0: + last_prec_with_zero_err = prec diff --git a/functional_algorithms/typesystem.py b/functional_algorithms/typesystem.py index 2416979..d6b162a 100644 --- a/functional_algorithms/typesystem.py +++ b/functional_algorithms/typesystem.py @@ -129,3 +129,8 @@ def is_same_kind(self, other): def asdtype(self): return getattr(numpy, str(self), None) + + def get_largest(self): + dtype = self.asdtype() + if dtype is not None: + return numpy.finfo(dtype).max diff --git a/functional_algorithms/utils.py b/functional_algorithms/utils.py index af302d1..8162467 100644 --- a/functional_algorithms/utils.py +++ b/functional_algorithms/utils.py @@ -1,5 +1,6 @@ import contextlib import itertools +import fractions import numpy import math import mpmath @@ -70,9 +71,11 @@ def mpf2float(dtype, x, flush_subnormals=False, prec=None, rounding=None): """ ctx = x.context if ctx.isfinite(x): - prec_rounding = ctx._prec_rounding + prec_rounding = ctx._prec_rounding[:] if prec is not None: prec_rounding[0] = prec + else: + prec_rounding[0] = get_precision(dtype) if rounding is not None: prec_rounding[1] = rounding sign, man, exp, bc = mpmath.libmp.normalize(*x._mpf_, *prec_rounding) @@ -204,6 +207,161 @@ def get_digits(x): return f"{sign}1p{e:+01d}" +def float2fraction(f): + """Convert floating-point number to Fraction. + + The conversion is exact. + """ + if isinstance(f, numpy.floating): + dtype = type(f) + fi = numpy.finfo(dtype) + itype = {numpy.float16: numpy.uint16, numpy.float32: numpy.uint32, numpy.float64: numpy.uint64}[dtype] + i = f.view(itype) + one = itype(1) + ssz = 1 # bit-size of sign part + esz = itype(fi.nexp) # bit-size of exponential part + fsz = itype(-1 - fi.negep) # bit-size of fractional part + fmask = itype((one << fsz) - one) + emask = itype((one << esz) - one) + umask = itype((one << (esz + fsz)) - one) + mxu = int(one << fsz) + + u = i & umask + + fpart = int(u & fmask) + epart = int((u >> fsz) & emask) + s = 1 if f < 0 else 0 + e = epart + fi.minexp - 1 + + if epart == 0 and fpart == 0: + # signed zero + num = 0 + denom = 1 - 2 * s + elif epart == 0: + # subnormals + num = (1 - 2 * s) * (fpart) + denom = mxu * (1 << (-e - 1)) + elif epart == emask and fpart == 0: + # infinity + num = (1 - 2 * s) * (1 << fi.maxexp) + denom = 1 + elif e < 0: + num = (1 - 2 * s) * (mxu + fpart) + denom = mxu * (1 << (-e)) + else: + num = (1 - 2 * s) * (mxu + fpart) * (1 << e) + denom = mxu + return fractions.Fraction(num, denom) + elif isinstance(f, float): + return float2fraction(numpy.float64(f)) + raise TypeError(f"float to fraction conversion requires floating-point input, got {type(f).__name__}") + + +def fraction2float(dtype, q): + """Convert Fraction to a floating-point number. + + The conversion may be inexact. + """ + fi = numpy.finfo(dtype) + num, denom = q.numerator, q.denominator + unum = abs(num) + if num == 0: + return dtype(0) if denom == 1 else -dtype(0) + elif denom == 1 and unum >= (1 << fi.maxexp): + return -dtype(numpy.inf) if num < 0 else dtype(numpy.inf) + else: + return dtype(num / denom) + + +def heron(x, niter=7): + """Find square root of an input as fraction using Heron's method. + + Consider sqrt(10005). Then the number of correct bits in the + returned value when converted to floating-point number, is: + + prec | niter + --------+------ + 23 | 1 + 51 | 2 + 102 | 3 + 206 | 4 + 412 | 5 + 828 | 6 + 1658 | 7 + + """ + num, denom = int(x**0.5), 1 + for i in range(niter): + num, denom = (num * num + x * denom * denom, 2 * denom * num) + return fractions.Fraction(num, denom) + + +def pi2fraction(n=3, niter=7): + """Return a fractional approximation of pi. + + Using Chudnovsky algorithm, see + + https://en.wikipedia.org/wiki/Chudnovsky_algorithm + + with Heron's method to compute sqrt(10005). + + The number of correct bits in the returned value of pi when + converted to a floating-point number, is: + + prec | n | niter + -----+----+------ + 91 | 2 | 3 + 139 | 3 | 4 + 187 | 4 | 4 + 235 | 5 | 5 + 281 | 6 | 5 + 330 | 7 | 5 + 376 | 8 | 5 + 424 | 9 | 6 + 470 | 10 | 6 + 518 | 11 | 6 + 564 | 12 | 6 + 612 | 13 | 6 + 658 | 14 | 6 + 706 | 15 | 6 + 752 | 16 | 6 + 801 | 17 | 6 + 846 | 18 | 7 + 894 | 19 | 7 + 940 | 20 | 7 + 987 | 21 | 7 + 1037 | 22 | 7 + 1082 | 23 | 7 + 1130 | 24 | 7 + 1178 | 25 | 7 + 1225 | 26 | 7 + 1272 | 27 | 7 + 1320 | 28 | 7 + ... + + """ + assert n >= 2 + + def bsplit(a, b): + if b == a + 1: + p = -(6 * a - 5) * (2 * a - 1) * (6 * a - 1) + q = 10939058860032000 * a**3 + r = p * (545140134 * a + 13591409) + else: + m = (a + b) // 2 + pa, qa, ra = bsplit(a, m) + pb, qb, rb = bsplit(m, b) + p = pa * pb + q = qa * qb + r = qb * ra + pa * rb + return p, q, r + + _, q, r = bsplit(1, n) + f = fractions.Fraction(426880 * q, 13591409 * q + r) + sq = heron(10005, niter=niter) + return sq * f + + def get_precision(x): if isinstance(x, numpy.ndarray): x = x.dtype.type @@ -255,8 +413,8 @@ def split_veltkamp(x, s=None, C=None): assert s >= 2 and s <= p - 2 C = type(x)(2**s + 1) g = C * x # for large x and s, this will overflow! - d = x - g - xh = g + d + d = g - x + xh = g - d xl = x - xh return xh, xl @@ -2064,10 +2222,10 @@ def multiword2mpf(ctx, mw): return s -def mpf2multiword(dtype, x, p=None, max_length=None): +def mpf2multiword(dtype, x, p=None, max_length=None, sexp=0): """Return a list of fixed-width floating point numbers such that - x == sum([float2mpf(mpmath.mp, v) for v in result]) + O(smallest subnormal of dtype) + x == sum([float2mpf(mpmath.mp, v) / (2 ** (i * sexp)) for i, v in enumerate(result)]) + O(...) where x is a mpmath mpf instance. @@ -2096,6 +2254,69 @@ def mpf2multiword(dtype, x, p=None, max_length=None): len(result) <= max_length holds. + + The truncation from the limited exponent size can be avoided by + specifying positive value to the scaling exponent argument sexp: + + Take x = pi: + p | sexp | maximal x precision in bits + --------+-------------+---------------------------- + float16 + 2 | 0,1,... | 11,11,... + 3 | 0,1,...[4] | 26,38,49,49,[49],40,25,18,17,11,... + 4 | 0,1,...[5] | 26,33,42,65,105,[105],63,34,24,20,... + 5 | 0,1,...[6] | 26,33,38,47,78,105,[105],69,33,29,... + 6 | 0,1,...[7] | 26,30,38,44,59,82,105,[105],73,38, + 7 | 0,1,...[8] | 26,30,34,42,54,61,87,150,[800],109,44,... + 8 | 0,1,...[9] | 26,29,33,38,42,53,63,76,122,[2978],187,... + 9 | 0,1,...[11] | ...,99,106,135,208,[357],99,... + 10 | 0,1,...[11] | ...,155,[1096],249,99,... + 11 | 0,1,...[13] | ...,99,114,208,451,150,... + float32 + 4 | 0,1,...[10] | ...,105,105,...,[105],103,99,... + 5 | 0,1,...[13] | ...,105,105,...,[105],93,... + 6 | 0,1,...[16] | ...,105,105,...,[105],92,... + 7 | 0,1,...[9] | ...,299,396,602,912,[912],871,... + 8 | 0,1,...[9] | ...,676,1343,[4280],1061,.... + 9 | 0,1,...[10] | ...,1205,[3726],1600,... + 10 | 0,1,...[11] | ...,1851,[16429],1182 + 11 | 0,1,...[12] | ...,1462,[>44000],1797 + 12 | 0,1,...[13] | ...,1823,[>50000],... + 13 | 0,1,...[14] | ...,1609,[>50000],1987,... + ... + 24 | 0,1,...[25] | ...,1738,3202,[>50000],... + float64 + 8 | 0,1,...[11] | ...,3188,4280,4280,4280,4280,[4280],3129,... + 12 | 0,1,...[13] | ...,13847,[>50000],13356,... + ... + 53 | 0,1,...,53,[..] | ...,55030,[...],... + + From the above table follows a relation + + sexp == p + 1 + + that maximizes the precision of x that can be represented exactly + as a multiword. + + The maximal bit-size of the multiword representation depends on + the value of x. For example, take sexp = p + 1, then for + p=1,...,11 the maximal bit-size sequence is as follows [float16]: + + pi : 4,4, 49,105,105,105,800,2978, 208,1096, 208 + log(2): 6,6,101, 19,101,139,101, 107,1345, 830, 596 + 2 / pi: 5,6, 6,129,127,322,324,2299,1093,1127,1339 + + that is, the optimal value for p also depends on the value of x. + + The dtype dependence of the maximal bit-size sequence is as + follows [2 / pi]: + + float16: 5,6,6,129,127,322,324,2299,1093,1127,1339 + float32: 5,6,6,129,127,322,324,2299,2835,[>5000] + float64: 5,6,6,129,127,322,324,2299,[>5000] + + that is, the optimal value for p increases with increasing dtype + bitsize. """ sign, man, exp, bc = x._mpf_ mpf = x.context.mpf @@ -2109,7 +2330,7 @@ def mpf2multiword(dtype, x, p=None, max_length=None): result = [] offset = max(bl - p, 0) if max_length is not None and max_length == 1: - result.append(mpf2float(dtype, x)) + result.append(mpf2float(dtype, x, prec=x.context.prec)) offset = 0 while True: man1 = (man & (mask << offset)) >> offset @@ -2122,9 +2343,10 @@ def mpf2multiword(dtype, x, p=None, max_length=None): offset -= d man1 = (man & (mask << offset)) >> offset bl1 = man1.bit_length() - exp1 = exp + offset - x1 = mpf2float(dtype, mpf((sign, man1, exp1, bl1))) - if x1 == dtype(0): + exp1 = exp + offset + len(result) * sexp + + x1 = mpf2float(dtype, mpf((sign, man1, exp1, bl1)), prec=x.context.prec) + if x1 == dtype(0) and offset == 0: # result represents truncated x break result.append(x1) @@ -2144,9 +2366,44 @@ def mpf2multiword(dtype, x, p=None, max_length=None): return result +def mpf2multiword_split(dtype, x, p=None, max_length=None): + """Return a list of fixed-width floating point numbers such that + + x == sum([float2mpf(mpmath.mp, v) for i, v in enumerate(result)]) + O(...) + + where x is a mpmath mpf instance. The result values mantissa fits into p bits. + + Different from mpf2multiword, the result may not be a monotonic sequence. + """ + tp = get_precision(dtype) + fi = numpy.finfo(dtype) + if p is None: + p = (tp + 1) // 2 + result = [] + ctx = x.context + + C = dtype(2**p + 1) + f = mpf2float(dtype, x) + while f != 0: + if max_length is not None and len(result) == max_length - 1: + result.append(f) + break + fh, fl = split_veltkamp(f, C=C) + result.append(fh) + assert split_veltkamp(fh, C=C)[1] == 0 + x = x - float2mpf(ctx, fh) + f = mpf2float(dtype, x) + + return result + + class NumpyContext: """A light-weight context for evaluating select with numpy inputs.""" + @property + def parameters(self): + return {} + def select(self, cond, x, y): assert isinstance(cond, (bool, numpy.bool_)) return x if cond else y @@ -2168,7 +2425,12 @@ def floor(self, value): return numpy.floor(value) assert 0, (value, type(value)) # unreachable - def trunc(self, value): + def ceil(self, value): + if isinstance(value, numpy.floating): + return numpy.ceil(value) + assert 0, (value, type(value)) # unreachable + + def truncate(self, value): if isinstance(value, numpy.floating): return numpy.trunc(value) assert 0, (value, type(value)) # unreachable @@ -2178,20 +2440,100 @@ def round(self, value): return numpy.round(value) assert 0, (value, type(value)) # unreachable + def rint(self, value): + if isinstance(value, numpy.floating): + return numpy.rint(value) + assert 0, (value, type(value)) # unreachable -def get_pi_over_two_multiword(dtype, prec=None, max_length=None): - if prec is None: - prec = {numpy.float16: 4, numpy.float32: 11, numpy.float64: 20}[dtype] + def remainder(self, value, other): + if isinstance(value, numpy.floating): + return numpy.remainder(value, other) + assert 0, (value, type(value)) # unreachable + + def fmod(self, value, other): + if isinstance(value, numpy.floating): + return numpy.fmod(value, other) + assert 0, (value, type(value)) # unreachable + + def sqrt(self, value): + if isinstance(value, numpy.floating): + return numpy.sqrt(value) + assert 0, (value, type(value)) # unreachable + + def _series(self, terms, params): + unit_index = params.get("unit_index", 0) + scaling_exp = params.get("scaling_exp", 0) + return ((unit_index, scaling_exp), *terms) + + def _get_series_operands(self, expr): + return expr + + def fma(self, x, y, z): + return x * y + z + + def upcast(self, x): + t = type(x).__name__ + return dict( + float16=numpy.float32, + float32=numpy.float64, + float64=numpy.float128, + )[ + t + ](x) + + def downcast(self, x): + t = type(x).__name__ + return dict( + float32=numpy.float16, + float64=numpy.float32, + longdouble=numpy.float64, + )[ + t + ](x) + + def upcast2(self, x): + t = type(x).__name__ + return dict( + float16=numpy.float64, + float32=numpy.float128, + )[ + t + ](x) + + def downcast2(self, x): + t = type(x).__name__ + return dict( + float64=numpy.float16, + longdouble=numpy.float32, + )[ + t + ](x) + + def logical_or(self, x, y): + return x or y + + def logical_and(self, x, y): + return x and y + + +def get_pi_over_two_multiword(dtype): max_prec = {numpy.float16: 24, numpy.float32: 149, numpy.float64: 1074}[dtype] ctx = mpmath.mp with ctx.workprec(max_prec): - return mpf2multiword(dtype, ctx.pi / 2, p=prec, max_length=max_length) + r_mp = ctx.pi / 2 + pi2h = mpf2float(dtype, r_mp) + pi2l = mpf2float(dtype, r_mp - float2mpf(ctx, pi2h)) + return pi2h, pi2l def get_two_over_pi_multiword(dtype, prec=None, max_length=None): if prec is None: - prec = {numpy.float16: 4, numpy.float32: 10, numpy.float64: 20}[dtype] + prec = {numpy.float16: 6, numpy.float32: 10, numpy.float64: 20}[dtype] + prec = {numpy.float16: 6, numpy.float32: 12, numpy.float64: 27}[dtype] max_prec = {numpy.float16: 24, numpy.float32: 149, numpy.float64: 1074}[dtype] ctx = mpmath.mp with ctx.workprec(max_prec): - return mpf2multiword(dtype, 2 / ctx.pi, p=prec, max_length=max_length) + r_mp = 2 / ctx.pi + if 0: + return mpf2multiword(dtype, r_mp, p=prec, max_length=max_length) + return mpf2multiword_split(dtype, r_mp, p=prec, max_length=max_length)