【发布时间】:2018-05-04 04:23:24
【问题描述】:
我正在尝试为二分法编写程序,并尝试在每次迭代时也绘制点。
这是我尝试过的代码。
Bisec = function(f,a =1, b =2, max=1e10, tol = 1e-100){
midVals = c()
for (i in 1:max){
c = (a+b)/2
midVals = append(midVals,c)
if(abs(f(c)) < tol){
return(list(c,plot(f),points(midVals)))
}else if(f(a)*f(c) > 0){
a = c
}else{
b =c
}
}
print("Maximum iterations reached")
}
x = var('x')
f = function(x){x*x-2}
Bisec(f,1, 3, max=1e5, tol = 1e-10)
我需要什么?
- 必须绘制函数 f。
- 在每次迭代中找到的中点应绘制在 x 轴上。
如何做到这一点?
任何提示都可能会有所帮助。我不知道我哪里错了。
【问题讨论】:
-
试试
return(list(c,plot(f),midVals))和x <- Bisec(f,1, 3, max=1e5, tol = 1)和plot(x[[2]]$x, x[[2]]$y, type="l", xlim=c(0,3)) points(x[[3]])。但我不知道你对你的观点有什么期望。 ` -
@StéphaneLaurent 我收到此错误
Error: unexpected symbol in "plot(x[[2]]$x, x[[2]]$y, type="l", xlim=c(0,3)) points" -
@StéphaneLaurent 关于
points(midVals):我试图在 xaxis 上显示迭代中计算的中点。 -
这里的问题离题了吗?应该移到codereview.stackexchange.com 吗?
-
不,codereview 是针对工作代码的。