install.packages('rootSolve')
install.packages('animation')
library(rootSolve)
use Newton’s Method to approximate all roots of the given func????ons accurate to 3 places aft????er the decimal.If an interval is given, find only the roots that lie in that interval. Use technology to obtain good ini????al approximati????ons.
func <- function(x) {
x^2 * cos(x) + (x-1) * sin(x)
}
curve(func, col = 'blue', lwd = 2, from = 0, n = 100, xlim=c(0, 5), ylab='f(x)')
abline(a=0, b=0, lty = 5)
uniroot(func, lower = 0, upper = 3,tol = .001)
## $root
## [1] 0
##
## $f.root
## [1] 0
##
## $iter
## [1] 0
##
## $init.it
## [1] NA
##
## $estim.prec
## [1] 0
#set initial x
x <- 2
while(TRUE){
if (x> -3 && x<3 ){
oldx = x
x = x^2 * cos(x) + (x-1) * sin(x)
print(x)
if (abs(abs(x)-abs(oldx))< 0.001){
break
}
}
}
## [1] -0.7552899
## [1] 1.618589
## [1] 0.492721
## [1] -0.02605988
## [1] 0.02741486
## [1] -0.02590865
## [1] 0.02724797
## [1] -0.02576006
## [1] 0.02708408
## [1] -0.02561403
## [1] 0.0269231
## [1] -0.02547049
## [1] 0.02676495
## [1] -0.02532937
## [1] 0.02660954
## [1] -0.0251906
## [1] 0.0264568
## [1] -0.02505412
## [1] 0.02630665
## [1] -0.02491986
## [1] 0.02615902
## [1] -0.02478776
## [1] 0.02601384
## [1] -0.02465777
## [1] 0.02587103
## [1] -0.02452983
## [1] 0.02573055
## [1] -0.02440388
## [1] 0.02559232
## [1] -0.02427988
## [1] 0.02545629
## [1] -0.02415777
## [1] 0.02532239
## [1] -0.02403751
## [1] 0.02519058
## [1] -0.02391905
## [1] 0.0250608
## [1] -0.02380235
## [1] 0.02493299
## [1] -0.02368736
## [1] 0.02480711
## [1] -0.02357404
## [1] 0.02468312
## [1] -0.02346235
## [1] 0.02456096
## [1] -0.02335225
## [1] 0.02444058
## [1] -0.0232437
## [1] 0.02432195
## [1] -0.02313667
## [1] 0.02420503
## [1] -0.02303113
## [1] 0.02408977
## [1] -0.02292703
## [1] 0.02397614
## [1] -0.02282435
## [1] 0.02386409
## [1] -0.02272305
## [1] 0.02375359
## [1] -0.0226231
## [1] 0.02364461
## [1] -0.02252448
## [1] 0.02353711
## [1] -0.02242715
## [1] 0.02343105
## [1] -0.02233108
## [1] 0.02332641
library(animation)
## Warning: package 'animation' was built under R version 3.4.2
ani.options(interval = 1, nmax = 50)
par(pch = 20)
showAnimation <- newton.method(FUN = function(x) x^2 * cos(x) + (x-1) * sin(x), init = 2, rg = c(-3, 10), tol = 0.001, interact = FALSE, col.lp = c("blue", "red", "red"))
showAnimation$root
## [1] 1.81328
combining the results above, we can see the roots are 0.023 and 1.813.