xref: /freebsd/contrib/arm-optimized-routines/math/tools/exp2.sollya (revision 31914882fca502069810b9e9ddea4bcd8136a4f4)
1*31914882SAlex Richardson// polynomial for approximating 2^x
2*31914882SAlex Richardson//
3*31914882SAlex Richardson// Copyright (c) 2019, Arm Limited.
4*31914882SAlex Richardson// SPDX-License-Identifier: MIT
5*31914882SAlex Richardson
6*31914882SAlex Richardson// exp2f parameters
7*31914882SAlex Richardsondeg = 3; // poly degree
8*31914882SAlex RichardsonN = 32;  // table entries
9*31914882SAlex Richardsonb = 1/(2*N); // interval
10*31914882SAlex Richardsona = -b;
11*31914882SAlex Richardson
12*31914882SAlex Richardson//// exp2 parameters
13*31914882SAlex Richardson//deg = 5; // poly degree
14*31914882SAlex Richardson//N = 128; // table entries
15*31914882SAlex Richardson//b = 1/(2*N); // interval
16*31914882SAlex Richardson//a = -b;
17*31914882SAlex Richardson
18*31914882SAlex Richardson// find polynomial with minimal relative error
19*31914882SAlex Richardson
20*31914882SAlex Richardsonf = 2^x;
21*31914882SAlex Richardson
22*31914882SAlex Richardson// return p that minimizes |f(x) - poly(x) - x^d*p(x)|/|f(x)|
23*31914882SAlex Richardsonapprox = proc(poly,d) {
24*31914882SAlex Richardson  return remez(1 - poly(x)/f(x), deg-d, [a;b], x^d/f(x), 1e-10);
25*31914882SAlex Richardson};
26*31914882SAlex Richardson// return p that minimizes |f(x) - poly(x) - x^d*p(x)|
27*31914882SAlex Richardsonapprox_abs = proc(poly,d) {
28*31914882SAlex Richardson  return remez(f(x) - poly(x), deg-d, [a;b], x^d, 1e-10);
29*31914882SAlex Richardson};
30*31914882SAlex Richardson
31*31914882SAlex Richardson// first coeff is fixed, iteratively find optimal double prec coeffs
32*31914882SAlex Richardsonpoly = 1;
33*31914882SAlex Richardsonfor i from 1 to deg do {
34*31914882SAlex Richardson  p = roundcoefficients(approx(poly,i), [|D ...|]);
35*31914882SAlex Richardson//  p = roundcoefficients(approx_abs(poly,i), [|D ...|]);
36*31914882SAlex Richardson  poly = poly + x^i*coeff(p,0);
37*31914882SAlex Richardson};
38*31914882SAlex Richardson
39*31914882SAlex Richardsondisplay = hexadecimal;
40*31914882SAlex Richardsonprint("rel error:", accurateinfnorm(1-poly(x)/2^x, [a;b], 30));
41*31914882SAlex Richardsonprint("abs error:", accurateinfnorm(2^x-poly(x), [a;b], 30));
42*31914882SAlex Richardsonprint("in [",a,b,"]");
43*31914882SAlex Richardson// double interval error for non-nearest rounding:
44*31914882SAlex Richardsonprint("rel2 error:", accurateinfnorm(1-poly(x)/2^x, [2*a;2*b], 30));
45*31914882SAlex Richardsonprint("abs2 error:", accurateinfnorm(2^x-poly(x), [2*a;2*b], 30));
46*31914882SAlex Richardsonprint("in [",2*a,2*b,"]");
47*31914882SAlex Richardsonprint("coeffs:");
48*31914882SAlex Richardsonfor i from 0 to deg do coeff(poly,i);
49