summaryrefslogtreecommitdiff
path: root/simulate_grade_hours.R
blob: d9c21f8324418b5ad3e8142d3cfbd3021e433178 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 某门课程的成绩与每周学习小时数关系举例(1)线性关系(2)非线性关系
# 蓝珲 2018年3月6日

# 定义函数
bound_data <- function(x, low, high) {
    y <- pmin(pmax(x, rep(low, length(x))), rep(high, length(x)))
}

linear_relationship <- function(x, a, b) {
    epsilon <- 10 + 7 * rnorm(length(x))
    y <- a + b * x + epsilon
    y <- bound_data(y, 0, 100) # make sure grades not lower than 0 nor higher than 100
}

nonlinear_relationship <- function(x) {
    epsilon <- 10 + 7 * rnorm(length(x))
    y <- -1.0 * (x - 10)^2 + 80 + epsilon # sometime extra effort means learning difficulty in this course
    y <- bound_data(y, 0, 100)
}

# 主程序
N <- 30 # number of students
hours <- sample(0:20, N, replace=T) # weekly hours of study
grade <- linear_relationship(hours, 20, 3)
plot(hours, grade, xlab='每周学习小时数', ylab='成绩', main='线性关系')

grade.2 <- nonlinear_relationship(hours)
plot(hours, grade.2, xlab='每周学习小时数', ylab='成绩', main='非线性关系')