HW1
- Write a loop that calculates 12-factorial
x <- 12
factorial <- 1
while (x>=1){
factorial <- factorial * x
x <- x - 1
}
print(factorial) # 479001600
## [1] 479001600
#check validation
print(factorial(12)==factorial) # True
## [1] TRUE
- Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
c(seq(20,50,by=5))
## [1] 20 25 30 35 40 45 50
#or
num_vec <- c(20:50)
num_vec[num_vec%%5==0]
## [1] 20 25 30 35 40 45 50
- Create the function “quadratic” that takes a trio of input numbers a, b, and c and solve the quadratic equation. The function should print as output the two solutions. \(x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}\)
calc_quad <- function(a,b,c){
result1 <- (-b+(b^2-4 * a * c) ^ (1/2)) / (2 * a)
result2 <- (-b-(b^2-4 * a * c) ^ (1/2)) / (2 * a)
print(result1)
print(result2)
}
calc_quad(a=3,b=7,c=4)
## [1] -1
## [1] -1.333333