I want to define families of polynomial functions for which I can compute the coefficients in advance. For example, (here I stop at degree 3)
function poly1(n::Int64, x)
if n == 0
return 1.
elseif n == 1
return x
elseif n == 2
return x^2 +0.595238x-7.875
elseif n == 3
return x^3 + 1.62521x^2 -12.8858x -8.111
end
end
I can also do a more generic code like
function poly2(n::Int64, x, coeff)
if n == 0
return 1.
else
X = [x^j for j in 0:n]
return coeff[n]'*X
end
end
where coeff
is an array of array here
coeff = [[0, 1.0],[-7.875, 0.595238, 1.0],[-8.111, -12.8858, 1.62521, 1.0] ]
The first one is far more efficient
using BenchmarkTools
@btime poly1(0,1.3);
0.021 ns (0 allocations: 0 bytes)
@btime poly1(1,1.3);
0.021 ns (0 allocations: 0 bytes)
@btime poly1(2,1.3);
0.021 ns (0 allocations: 0 bytes)
@btime poly2(0,1.3,coeff);
26.810 ns (1 allocation: 16 bytes)
@btime poly2(1,1.3,coeff);
94.884 ns (2 allocations: 112 bytes)
@btime poly2(2,1.3,coeff);
103.483 ns (2 allocations: 128 bytes)
My question is how to define automatically in advance (once I know the coeff
array), my polynomial functions for n=0:nmax
as in poly1
the most efficiently? (Because I need to call these functions a lot of time after)