131914882SAlex Richardson// polynomial for approximating 2^x 231914882SAlex Richardson// 331914882SAlex Richardson// Copyright (c) 2019, Arm Limited. 4*072a4ba8SAndrew Turner// SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception 531914882SAlex Richardson 631914882SAlex Richardson// exp2f parameters 731914882SAlex Richardsondeg = 3; // poly degree 831914882SAlex RichardsonN = 32; // table entries 931914882SAlex Richardsonb = 1/(2*N); // interval 1031914882SAlex Richardsona = -b; 1131914882SAlex Richardson 1231914882SAlex Richardson//// exp2 parameters 1331914882SAlex Richardson//deg = 5; // poly degree 1431914882SAlex Richardson//N = 128; // table entries 1531914882SAlex Richardson//b = 1/(2*N); // interval 1631914882SAlex Richardson//a = -b; 1731914882SAlex Richardson 1831914882SAlex Richardson// find polynomial with minimal relative error 1931914882SAlex Richardson 2031914882SAlex Richardsonf = 2^x; 2131914882SAlex Richardson 2231914882SAlex Richardson// return p that minimizes |f(x) - poly(x) - x^d*p(x)|/|f(x)| 2331914882SAlex Richardsonapprox = proc(poly,d) { 2431914882SAlex Richardson return remez(1 - poly(x)/f(x), deg-d, [a;b], x^d/f(x), 1e-10); 2531914882SAlex Richardson}; 2631914882SAlex Richardson// return p that minimizes |f(x) - poly(x) - x^d*p(x)| 2731914882SAlex Richardsonapprox_abs = proc(poly,d) { 2831914882SAlex Richardson return remez(f(x) - poly(x), deg-d, [a;b], x^d, 1e-10); 2931914882SAlex Richardson}; 3031914882SAlex Richardson 3131914882SAlex Richardson// first coeff is fixed, iteratively find optimal double prec coeffs 3231914882SAlex Richardsonpoly = 1; 3331914882SAlex Richardsonfor i from 1 to deg do { 3431914882SAlex Richardson p = roundcoefficients(approx(poly,i), [|D ...|]); 3531914882SAlex Richardson// p = roundcoefficients(approx_abs(poly,i), [|D ...|]); 3631914882SAlex Richardson poly = poly + x^i*coeff(p,0); 3731914882SAlex Richardson}; 3831914882SAlex Richardson 3931914882SAlex Richardsondisplay = hexadecimal; 4031914882SAlex Richardsonprint("rel error:", accurateinfnorm(1-poly(x)/2^x, [a;b], 30)); 4131914882SAlex Richardsonprint("abs error:", accurateinfnorm(2^x-poly(x), [a;b], 30)); 4231914882SAlex Richardsonprint("in [",a,b,"]"); 4331914882SAlex Richardson// double interval error for non-nearest rounding: 4431914882SAlex Richardsonprint("rel2 error:", accurateinfnorm(1-poly(x)/2^x, [2*a;2*b], 30)); 4531914882SAlex Richardsonprint("abs2 error:", accurateinfnorm(2^x-poly(x), [2*a;2*b], 30)); 4631914882SAlex Richardsonprint("in [",2*a,2*b,"]"); 4731914882SAlex Richardsonprint("coeffs:"); 4831914882SAlex Richardsonfor i from 0 to deg do coeff(poly,i); 49