# R语言的科学编程与仿真-第三章习题解答
#chapter 3
# problem 1
if (x <= 0){
y = -x^3
} else if(x>0 & x<=1){
y = x^2
} else {
y = sqrt(x)
}
# input
x.values <- seq(-2,2,by=0.1)
# for each x calculate y
n <- length(x.values)
y.values <- rep(0,n)
for (i in 1:n){
x <- x.values[i]
# x <- 0.5
# expression for y
if (x <= 0){
y = -x^3
} else if(x>0 & x<=1){
y = x^2
} else {
y = sqrt(x)
}
y.values[i] <- y
}
# output
plot(x.values,y.values,type = "l")
题一图:
# problem 2
# 参数初始化
x <- 6.6
n <- 8
h <- 0
for(i in 0:n){
h = h + x^i
}
# x=0.3 n=55 outcome = [1] 1.428571428571429
# x=6.6 n= 8 outcome = [1] 4243335.538178558
# 函数式编程
h <- function(x,n){
k <- rep(0,n+1)
for(i in 0:n){
k[i]= x^i # 因为k[i]只能从k[1]开始,这里x^0无法赋值给k[0]
}
return(sum(k)+1) # 故,这里需要将x^0=1加上
}
h(n=4,x=2) # 可以验证 h(n=4,x=2)=31
# problem 3
h(0.3,55) # outcome [1] 1.428571
options(digits = 16) # 没有这行命令,结果为[1] 4243336
h(6.6,8) # 结果 [1] 4243335.538178558
# 结果与书上的一致,证明题二的编程是正确的
# problem 4
# 用 while 循环
# 参数初始化
x <- .3
n <- 55
i <- 0
h <- 0
while(i <= n){
h = h+ x^i
i = i + 1
}
# 可以验证上述程序的结果与书上的一致
# 向量化
x <- 0.3
n <- 55
i <- seq(0,n,by=1)
h <- sum(x^i)
# 函数化
h <- function(x,n){
i = seq(0,n,by = 1)
return(sum(x^i))
}
# 可以验证 h(0.3,55),h(6.6,8)与书上的结果一致
# problem 5
v <- matrix(c(2,2),nrow = 2,ncol = 1) # 生成一个二维列向量
vec <-as.vector(c(2,2)) # 生成一个二维行向量
theta <- pi/2 # 旋转角度
t <- matrix(c(cos(theta),-sin(theta),sin(theta),cos(theta)),nrow = 2,ncol = 2,byrow = T)
vec%*%t # 行向量右乘旋转矩阵
# [,1] [,2]
# [1,] 2 -2
t%*%v # 列向量左乘旋转矩阵
# [,1]
# [1,] -2
# [2,] 2
# problem 6
# 用循环
x <- seq(1,10,by=1)
h <- 1
for(i in 1:10){
h=h*sqrt(x[i])
}
# h = [1] 1904.941
# 向量化
sqrt(prod(x))
# [1] 1904.941
# problem 7
y <- seq(1,100,by=1)
y.sum <- sum(y[which(y %% 3 == 0 )])
# problem 8
# xian fang yi xia
# problem 9
# 略
# problem 10
x <- seq(100,1,by=-1)
x <- c(3,6,2,7,1,5,6,9,10,5,20,41,23,15,74,92,6)
x.min <- x[1]
for(i in 1:length(x)){
if(x.min <= x[i]){
x.min = x.min
} else {
x.min = x[i]
}
}
# x.min = [1] 1
# problem 11
# 没怎么看懂题目
# 不能用sort 函数的话,也就是需要自己编写排序算法
# problem 12
x <- sum(ceiling(6*runif(2)))
if (x == 7 || x == 11){
cat(" I am the winner")
} else if (x == sum(ceiling(6*runif(2)))){
cat(" i am the winner")
} else {
cat(" you are the loser")
}
# 选中以上程序,多次运行可以验证,该程序能随机输出
# I am the winner, i am the winner, you are the loser 这三句
# problem 13
t <- seq(0,10,by=0.01)
xvalues <- sqrt(t)*cos(2*pi*t)
yvalues <- sqrt(t)*sin(2*pi*t)
plot(xvalues,yvalues,type = "l")
# 也可以用类似 题一 的方式
t <- seq(0,10,by=0.01)
x <- rep(0,length(t))
y <- rep(0,length(t))
for(i in 1:length(t)){
x[i] = sqrt(t[i])*cos(2*pi*t[i])
y[i] = sqrt(t[i])*sin(2*pi*t[i])
}
plot(x,y,type = "l")
# 可以验证,这两种方式画出的图是一样的
题13图:
by = 0.1:
by = 0.01