"""Reduce Karpov's 20 equal-area equations to three scalar equations.""" import argparse from decimal import Decimal, localcontext from pathlib import Path def determinant(p, q, r): x, y = p u, v = q a, b = r return (u - x) * (b - y) - (v - y) * (a - x) def intersect(p, q, goal, r, s, other_goal): """Solve det(p,q,z) = goal and det(r,s,z) = other_goal for z.""" a, b = p[1] - q[1], q[0] - p[0] c, d = r[1] - s[1], s[0] - r[0] u = goal + a * p[0] + b * p[1] v = other_goal + c * r[0] + d * r[1] cross = a * d - b * c return (u * d - b * v) / cross, (a * v - u * c) / cross def reduced(alpha, beta, height): """Return normalized points, width, and three contact residuals.""" p1, p5, p6, p9, p11 = (0, height), (beta, 0), (0, 1), (1, alpha), (1, 0) slope = beta - 2 - alpha ratio = alpha / (1 + slope) p12 = (1 + ratio, slope * ratio) shift = alpha / (beta * p12[1] - beta + p12[0]) p0 = (p12[0] + beta * shift, p12[1] - shift) gap = alpha * (2 * height - p0[1]) / ( height * p0[0] - beta * (height - p0[1]) ) p8 = ((alpha + beta * gap) / height, height - gap) at_zero = determinant(p6, p8, p9) slope_along_line = determinant((1, 1 + slope), p8, p9) - at_zero width = (alpha - at_zero) / slope_along_line p7 = (width, 1 + slope * width) p2 = intersect(p0, p7, alpha, p8, p9, -alpha) p3 = intersect(p2, p5, -alpha, p7, p8, alpha) p4 = (beta + ((p3[0] - beta) * height - alpha) / p3[1], height) p10 = intersect(p8, p11, -alpha, p8, p12, alpha) residuals = ( determinant(p0, p3, p10) - alpha, determinant(p2, p4, p10) - alpha, determinant(p4, p6, p8) + alpha, ) return (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12), width, residuals def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("coordinates", type=Path, help="60-decimal output of polish.py in published order") args = parser.parse_args() with localcontext() as ctx: ctx.prec = 90 points = [tuple(map(Decimal, line.split())) for line in args.coordinates.read_text().splitlines() if line.strip() and not line.lstrip().startswith("#")] if len(points) != 13: parser.error("expected 13 points in the published order") scale_x = points[11][0] scale_y = points[6][1] alpha, beta, height = points[9][1] / scale_y, points[5][0] / scale_x, 1 / scale_y actual, width, residuals = reduced(alpha, beta, height) reconstructed = [(x / width, y / height) for x, y in actual] coordinate_error = max(abs(a - b) for x, y in zip(points, reconstructed) for a, b in zip(x, y)) assert max(map(abs, residuals)) < Decimal("1e-52") assert coordinate_error < Decimal("1e-53") print("alpha, beta, height", *(f"{x:.44f}" for x in (alpha, beta, height))) print("width", f"{width:.44f}") print("minimum area from normalized variables", f"{alpha / (2 * width * height):.52f}") print("maximum residual", max(map(abs, residuals))) print("maximum coordinate error", coordinate_error) if __name__ == "__main__": main()