Solving functions in R

2020-04-10 13:45发布

I have following function:

2.3366*x^1+(-3.2684)*x^2+3.6513*x^3+(-2.2608)*x^5+2.1501*x^13+(-2.7412)*x^21+1.8876*x^34 = 0.8232711

I need to solve x.

In MATLAB I would use following:

fsolve(function1=15/18.22,x)

How do I do this in R? Can I use solve or uniroot or something else?

标签: r
2条回答
手持菜刀,她持情操
2楼-- · 2020-04-10 14:30

Use polyroot :

xx = c(-0.8232711,2.3366,-3.2684,3.6513,0,-2.2608,rep(0,13-6),
    2.1501,rep(0,21-14),-2.7412,rep(0,34-22),1.8876)
polyroot(xx)

round(polyroot(xx),2)
 [1]  0.58+0.00i  0.12+0.63i  0.12-0.63i  0.83-0.21i  0.21+1.02i -0.97+0.35i -0.18-0.99i  0.97-0.06i
 [9]  0.60+0.81i -1.03+0.00i  0.21-1.02i  0.83+0.21i -0.18+0.99i -1.03-0.23i  0.05-1.02i  0.97+0.06i
[17]  0.05+1.02i -1.03+0.23i  0.60-0.81i  0.75+0.63i -0.58+0.85i -0.76-0.74i  0.75-0.63i  0.52+0.88i
[25] -0.87+0.60i -0.58-0.85i  0.95-0.48i -0.40+1.01i -0.40-1.01i  0.95+0.48i -0.76+0.74i -0.97-0.35i
[33]  0.52-0.88i -0.87-0.60i

You can check that you have the right polynom using this :

library(polynom)
as.polynomial(xx)
-0.8232711 + 2.3366*x - 3.2684*x^2 + 3.6513*x^3 - 2.2608*x^5 + 2.1501*x^13 - 2.7412*x^21 +  
1.8876*x^34 
查看更多
家丑人穷心不美
3楼-- · 2020-04-10 14:36

Thanks for the answers. Figured it out myself.

f1<-function(z) {(2.3366*z^1+(-3.2684)*z^2+3.6513*z^3+(-2.2608)*z^5+2.1501*z^13+(-2.7412)*z^21+1.8876*z^34)-0.8232711}
Z <- uniroot(f1,c(0,1))
Z1 <-Z$root
Z1
查看更多
登录 后发表回答