1// polynomial for approximating sin(x)
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7deg = 7;   // polynomial degree
8a = -pi/4; // interval
9b = pi/4;
10
11// find even polynomial with minimal abs error compared to sin(x)/x
12
13// account for /x
14deg = deg-1;
15
16// f = sin(x)/x;
17f = 1;
18c = 1;
19for i from 1 to 60 do { c = 2*i*(2*i + 1)*c; f = f + (-1)^i*x^(2*i)/c; };
20
21// return p that minimizes |f(x) - poly(x) - x^d*p(x)|
22approx = proc(poly,d) {
23  return remez(f(x)-poly(x), deg-d, [a;b], x^d, 1e-10);
24};
25
26// first coeff is fixed, iteratively find optimal double prec coeffs
27poly = 1;
28for i from 1 to deg/2 do {
29  p = roundcoefficients(approx(poly,2*i), [|D ...|]);
30  poly = poly + x^(2*i)*coeff(p,0);
31};
32
33display = hexadecimal;
34print("rel error:", accurateinfnorm(1-poly(x)/f(x), [a;b], 30));
35print("abs error:", accurateinfnorm(sin(x)-x*poly(x), [a;b], 30));
36print("in [",a,b,"]");
37print("coeffs:");
38for i from 0 to deg do coeff(poly,i);
39