R Bridge Week 1 Assignment
- Write a loop that calculates 12 factorial
# Loop That calculate 12 factorial
n_factional <- function(number){
fract = 1
#vector = 0
# Check is vector is not negative
if (number < 0) {
print("factorial negative is not defined")
}
else if (number == 0 ) {
return(1)
}
else {
for (i in 1:number){
fract <- fract * i
}
return(fract)
}
}
n_factional(12)
## [1] 479001600
- Show how to create a numeric vector that contains the sequence from
20 to 50 by 5.
vector <- seq(from=20,to=50, by=5)
vector
## [1] 20 25 30 35 40 45 50
is.numeric(vector)
## [1] TRUE
- Create the function “quad” 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. Please run and test your answer for (1,2,1),
(1,6,5) and (1,1,1).
# write quadratic equatio
quad <- function(a,b,c) {
## provide baseline for equation
print(paste0("You have chosen the quadratic equation ",
a, "x^2 + ", b, "x + ", c, "."))
# discriminant formula
f <- (b^2) - (4*a*c)
# discriminant is less than zero, the quadratic equations has no roots
if(f < 0){
return(paste0(" No real Number found"))
# if discriminant is superior than zero, two intercepts will be generated
}else if(f > 0){
x_1 <- (-b + sqrt(f)) /(2*a)
x_2 <- (-b - sqrt(f)) / (2*a)
return(paste0("The Two x-intercepts are: ",
format(round(x_1, 5), nsmall = 5), " and ",
format(round(x_2, 5), nsmall = 5), "."))
# if discriminant is equal zero
}else{
x <- (-b) /(2*a)
return(x)
}
}
# (1,2,1), (1,6,5) and (1,1,1).
vec1 <- quad(1,2,1)
## [1] "You have chosen the quadratic equation 1x^2 + 2x + 1."
vec1
## [1] -1
vec2 <- quad(1,-4,1)
## [1] "You have chosen the quadratic equation 1x^2 + -4x + 1."
vec2
## [1] "The Two x-intercepts are: 3.73205 and 0.26795."
vec3 <- quad(1,1,1)
## [1] "You have chosen the quadratic equation 1x^2 + 1x + 1."
vec3
## [1] " No real Number found"