二分法
R语言编程:
#(二分法)
dichotomy<-function(f,a,b,eps=1e-5){
if(f(a)*f(b)>0)
list(fail="find root is fail!")
else{
repeat{
if(abs(b-a)<eps) break;
x<-(a+b)/2
if(f(a)*f(x)<0) b<-x else a<-x
}
list(root=(a+b)/2,fun=f(x))
}
}
f<-function(x) x^3-x-1
dichotomy(f,1,2)
dichotomy(f,0,1)
其中函数说明
结果
> dichotomy<-function(f,a,b,eps=1e-5){
+ if(f(a)*f(b)>0)
+ list(fail="find root is fail!")
+ else{
+ repeat{
+ if(abs(b-a)<eps) break;
+ x<-(a+b)/2
+ if(f(a)*f(x)<0) b<-x else a<-x
+ }
+ list(root=(a+b)/2,fun=f(x))
+ }
+ }
> f<-function(x) x^3-x-1
> dichotomy(f,1,2)
$`root`
[1] 1.324718
$fun
[1] -1.405875e-05
> dichotomy(f,0,1)
$`fail`
[1] "find root is fail!"
如:
uniroot(f,c(1,2))
uniroot(f,c(0,1))
> uniroot(f,c(1,2))
$`root`
[1] 1.324718
$f.root
[1] -5.634261e-07
$iter
[1] 7
$init.it
[1] NA
$estim.prec
[1] 6.103516e-05
> uniroot(f,c(0,1))
Error in uniroot(f, c(0, 1)) : 位于极点边的f()值之正负号不相反
其他关于uniroot使用见网址
作业题:
##三个其他函数uniroot法
f1<-function(x) 2*x^3-6*x-1
x<-seq(-2,2,0.01)
plot(x,f1(x),type = "l")
abline(h=0,v=c(-5:5))
result=uniroot(f1,c(-2,-1),tol=1e-6)
result$root
result=uniroot(f1,c(-1,0),tol=1e-6)
result$root
result=uniroot(f1,c(-1,0),tol=1e-6)
result$root
##
f2<-function(x) exp(x-2)+x^3-x
x<-seq(-2,2,0.01)
plot(x,f2(x),type = "l")
abline(h=0,v=c(-5:5))
result=uniroot(f2,c(-1.5,-0.5),tol=1e-6)
result$root
result=uniroot(f2,c(-0.5,0.5),tol=1e-6)
result$root
result=uniroot(f2,c(0.5,1.5),tol=1e-6)
result$root
##
f3<-function(x) 1+5*x-6*x^3-exp(2*x)
x<-seq(-1,1,0.01)
plot(x,f3(x),type = "l")
abline(h=0,v=c(-5:5))
result=uniroot(f3,c(-1,-0.5),tol=1e-6)
result$root
result=uniroot(f3,c(-0.5,0.2),tol=1e-6)
result$root
result=uniroot(f3,c(0.2,1),tol=1e-6)
result$root
tip: uniroot中tol表示精确度,result$root表示取其中root值
- abline(h=yvalues, v=xvalues)
表示画参考线:
abline(h = c(1, 5)) #则在y=1和5处各有一条水平线
abline(v = c(1, 5)) #则在x=1和5处各有一条垂直线
结果
> ##三个其他函数uniroot法
> f1<-function(x) 2*x^3-6*x-1
> x<-seq(-2,2,0.01)
> plot(x,f1(x),type = "l")
> abline(h=0,v=c(-5:5))
>
> result=uniroot(f1,c(-2,-1),tol=1e-6)
> result$root
[1] -1.641784
> result=uniroot(f1,c(-1,0),tol=1e-6)
> result$root
[1] -0.1682544
> result=uniroot(f1,c(-1,0),tol=1e-6)
> result$root
[1] -0.1682544
> ##
> f2<-function(x) exp(x-2)+x^3-x
> x<-seq(-2,2,0.01)
> plot(x,f2(x),type = "l")
> abline(h=0,v=c(-5:5))
>
> result=uniroot(f2,c(-1.5,-0.5),tol=1e-6)
> result$root
[1] -1.023482
> result=uniroot(f2,c(-0.5,0.5),tol=1e-6)
> result$root
[1] 0.1638222
> result=uniroot(f2,c(0.5,1.5),tol=1e-6)
> result$root
[1] 0.7889413
> f3<-function(x) 1+5*x-6*x^3-exp(2*x)
> x<-seq(-1,1,0.01)
> plot(x,f3(x),type = "l")
> abline(h=0,v=c(-5:5))
>
> result=uniroot(f3,c(-1,-0.5),tol=1e-6)
> result$root
[1] -0.8180937
> result=uniroot(f3,c(-0.5,0.2),tol=1e-6)
> result$root
[1] -5.66292e-11
> result=uniroot(f3,c(0.2,1),tol=1e-6)
> result$root
[1] 0.5063083