R1 Lecture 06 Class Notes
YU,Xiang
Apr 7 2015
作业答疑
fib2 <- function(N){
f <- c(1,1)
i <- 1
while(f[i]+f[i+1]<=N){
f[i+2] <- f[i]+f[i+1]
i <- i+1
}
f
}
开方的实现
写一个函数
sqrt2 <- function(x){…}
输出x的平方根
步骤
1.目标函数是 f=x^2-n
2.定义初始区间 I=[a,b],保证 f 在 I 的端点上异号
3.检验 I 的中点 c=(a+b)/2 位置的 f值, 生成新的区间
4.重复 3 直到 f值小于可接受的误差值(比如 0.00001)
sqrt2 <- function(n){
f <- function(x) x^2-n
if(n>=1){
interval <- c(0,n)
}
else{
interval <- c(0,1)
}
while(abs(f(mean(interval)))>0.0001){
a <- interval[1]
b <- interval[2]
c <- mean(interval)
if(f(a)*f(c)<0){
interval <- c(a,c)
}
else{
interval <- c(c,b)
}
}
mean(interval)
}
基础画图
散点图
# 在(1,1)画一个点
plot(x=1,y=1)
# 在(1,1),(2,2),(3,3)处各画一个点
plot(1:3,1:3)
# with colors
plot(1:3,1:3,col='red')
plot(1:10,1:10,col=1:10)
# with pch and cex
plot(1:25,1:25,pch=1:25,cex=3,col=1:25)
# 画出函数图像
# y=x^2+x-6 在 [-5,5] 上的图像是?
x <- seq(-5,5,0.1)
y <- x^2+x-6
plot(x,y)
plot(x,y,type="l") # "p" for point, "l" for line, "n" for none
# lwd for line width, lty for line type
练习 画出如下分段函数在 [−5,5] 的图像
y={ex|x>0}or{x2|x⩽0}
$$ # 上面的公式写的不好看,因为不知为何
y=\begin{cases} # 左边这个分段函数的Latex公式
e^{x} & x>0 # 在网页上无法分两行显示,
x^{2} & x<0 # 确认其在tex->pdf中是正常的,
\end{cases} # 莫非是mathml的问题?
$$
x <- seq(-5,5,0.1)
y <- exp(x)
y[x<=0] <- (x[x<=0])^2
plot(x,y,type="l")
第六周作业
1
1000000以内根据3x+1算法最慢收敛的10个数是谁?
x3p1_slowest <- function(N,m){
...
}
x3p1_slowest(N=1000000,m=10)
2
熟悉 plot 中各个参数的用法和效果