nls的数据源必须有误差。不能精确等于公式返回值(零残差)。循环次数大于50通常是使用 函数精确返回值 作为数据源去拟合函数。必须给y值加上随机误差。
z=function(x,a,b){a*sin(x)+b*cos(x)}x=seq(1,10,9/500)
y=z(x,1,1) # a=1 b=1 是期望拟合出的结果。
cor=data.frame(x=x,y=y)
cor$res=runif(length(cor$x),min=-0.005,max=0.005)
cor$yres=cor$y+cor$res
#yres =y加上随机误差,y是精确返回值
> nls(cor$yres~z(cor$x,a,b),data=cor,start=list(a=0.8,b=1.3))
Nonlinear regression model
model: cor$yres ~ z(cor$x, a, b)
data: cor
a b
0.9999 1.0002
residual sum-of-squares: 0.004213
Number of iterations to convergence: 1
Achieved convergence tolerance: 2.554e-07
#使用精确返回值拟合就会出错。
> nls(cor$y~z(cor$x,a,b),data=cor,start=list(a=1,b=1))
Error in nls(cor$y ~ z(cor$x, a, b), data = cor, start = list(a = 1, b = 1)) :
循环次数超过了50这个最大值
for循环是通过变量或者向量控制循环。while循环是另一种循环,通过一个逻辑判定准则来控制循环。
while循环的语法为
例1 下面我们通过while循环来计算
运行程序
next语句用于跳出当前一轮的循环,执行下一轮循环。而break语句是跳出当前循环,不再执行下一轮循环。
例2 计算