How to find the points where a polynomial fit passes through zero

569 views Asked by At

I've fit a 4th order polynomial curve to my data like so:

y<-c(-13,16,35,40,28,36,43,33,40,33,22,-5,-27,-31,-29,-25,-26,-31,-26,-24,-25,-29,-23,4)
x<-1:24

#4th order polynomial fit
fit<-lm(y~poly(x,4,raw=TRUE))

plot(x,y,ylim=c(min(y)-10,max(y)+10))
lines(x,predict(fit,data.frame(x=x)),col="red")
abline(h=0,lty=2)

My final goal would be to calculate the 3 points of this curve where it meets the zero line.

So first, I need to extend the end of the curve fit so it passes beyond the zero line for a third time. Once I have done this, I would want to calculate the 3 points where this equation passes through the zero line.

1

There are 1 answers

2
MrFlick On BEST ANSWER

You can use the predict function to get values from your fitted model. For example

pred <- function(x) predict(fit, newdata=data.frame(x=x))

Then if you want multiple roots, you can use a function like uniroot.all from the rootSolve package

rootSolve::uniroot.all(pred, c(0,30))
# 1.428859 11.990087 24.420745

which will find the roots between 0 and 30 from your model. You could also call the base function uniroot multiple times.