How to fit a polynomial with a pre-determined degree to a set of points?

Hugo
Wed, 21 Dec 2022 22:14:38 +0000
General Usage

Hi, all

I want to approximate a function to a vector v of 99 values so I can evaluate that function over other values. This can be a simple linear interpolation of the 99 values, but I’d fit a polynomial in case other values don’t fit within the range of the 99 values.

Initially, I thought of using Polynomials.jl to apply the function fromroots as shown in the Quick Start examples of the package’s page.

using Polynomials
poly = fromroots(v)
poly(1250) # This could be any other number from 0 to 100,000

But the resulting polynomial is rife with monomials of powers that go as high as 99. Many of these monomials have Inf32 for coefficients. The evaluation step didn’t work. I did not find a way to limit the maximum degree to the polynomial. A degree of 10, for instance, would be just fine.

Then, thanks an example from the Julia Discord, I found a different way I attempt to implement

using Polynomials
fit(x,v, 10)

Here, x has the same length as v. However, to my surprise, I got the following error message:

ERROR: UndefVarError: fit not defined

I have the Distributions.jl also in use and I wonder if this is somehow the reason why fit won’t work (Distributions.jl also has a function called fit). I don’t know how to specify the package for a function. In R, I would’ve done Polynomials::fit, but in Julia that’s no kosher. I searched online for a way to specify the package, but given the results I got, I’m sure I am not framing my search correctly.

Lastly, I learned about ApproxFun.jl. The package has a brief section on “Using ApproxFun for “manual” interpolation”, which seemed just what I have been looking for. However, to achieve such manual interpolation, I must pass a function f and a domain to the function Fun. The problem is that I’m looking for a function f so I can’t provide it.

Does anyone know how I find a polynomial of a degree D to a set of N numbers so I can use the polynomial to be evaluate at other input values?

# This simple example will reproduce the error I'm having using the function fit.
#
using Polynomials
x = 0.01:0.01:0.99
y = (x.^2).*5 - x.*2 .+ 6
fit(x, y, 10)

8 posts - 4 participants