| # SPDX-FileCopyrightText: The Eigen Authors | |
| # SPDX-License-Identifier: MPL-2.0 | |
| """Reproduce the AVX2 binary64 cbrt seed using a relative Remez fit.""" | |
| from decimal import Decimal, localcontext | |
| from math import comb, cos, pi | |
| def solve(rows): | |
| for i in range(len(rows)): | |
| pivot = max(range(i, len(rows)), key=lambda j: abs(rows[j][i])) | |
| rows[i], rows[pivot] = rows[pivot], rows[i] | |
| scale = rows[i][i] | |
| rows[i] = [element / scale for element in rows[i]] | |
| for j, row in enumerate(rows): | |
| if i != j: | |
| rows[j] = [a - row[i] * b for a, b in zip(row, rows[i])] | |
| return [row[-1] for row in rows] | |
| def polynomial(coeffs, x): | |
| return sum(coefficient * x**i for i, coefficient in enumerate(coeffs)) | |
| def generate(): | |
| with localcontext() as context: | |
| context.prec = 75 | |
| one_third = Decimal(1) / 3 | |
| degree = 6 | |
| points = [Decimal(0.75 - 0.25 * cos(pi * i / 7)) for i in range(8)] | |
| for _ in range(10): | |
| coeffs = solve([ | |
| [x**one_third * (4 * x - 3)**j for j in range(degree + 1)] | |
| + [Decimal((-1)**i), Decimal(1)] | |
| for i, x in enumerate(points) | |
| ])[:-1] | |
| # The extrema of x^(1/3)*P(x) satisfy P(x) + 3*x*P'(x) = 0. | |
| # Set t = 4*x - 3 and differentiate the resulting polynomial in t. | |
| stationary = [ | |
| (1 + 3 * i) * coeff | |
| + (9 * (i + 1) * coeffs[i + 1] if i < degree else 0) | |
| for i, coeff in enumerate(coeffs) | |
| ] | |
| derivative = [i * stationary[i] for i in range(1, degree + 1)] | |
| extrema = [Decimal("0.5")] | |
| for x in points[1:-1]: | |
| t = 4 * x - 3 | |
| for _ in range(15): | |
| t -= polynomial(stationary, t) / polynomial(derivative, t) | |
| extrema.append((t + 3) / 4) | |
| points = extrema + [Decimal(1)] | |
| for j in range(degree + 1): | |
| coefficient = sum( | |
| coeffs[i] * comb(i, j) * 4**j * (-3)**(i - j) | |
| for i in range(j, degree + 1) | |
| ) | |
| print(repr(float(coefficient))) | |
| if __name__ == "__main__": | |
| generate() |