# Copyright Avraham Adler (c) 2023
# SPDX-License-Identifier: MPL-2.0+

tol <- sqrt(.Machine$double.eps)

opts <- list(maxiter = 100L, miniter = 10L, conviter = 10L,
             showProgress = FALSE, convRatio = 1.000000001, tol = 1e-14,
             ztol = .Machine$double.eps)

# Test polyMat
x <- c(-0.4, 0.1, 0.3, 0.4)
control <- matrix(c(rep(1, 4L), x, x ^ 2, 1, -1, 1, -1), nrow = 4)
expect_identical(minimaxApprox:::polyMat(x, y = NULL, relErr = FALSE,
                                         basis = "m"), control)

# Test polyCoeffs
# If the function is a pure polynomial then coeffs should recover it exactly.
# Therefore for, for 4 data points and the function x² + 2x + 3, the
# coefficients should return c(3, 2, 1) and the error should be 0.
fn <- function(x) x ^ 2 + 2 * x + 3
x <- seq(0, 2, length.out = 4)
control <- c(3, 2, 1)
PP <- minimaxApprox:::polyCoeffs(x, fn, TRUE, "m", 0, 2, opts$ztol)
expect_equal(PP$a, control, tolerance = tol)
expect_equal(PP$E, 0, tolerance = tol)
