- Write a loop that calculates 12-factorial
Factorial <- 1
for(i in 1:12)
{
Factorial <- Factorial * i
}
- Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
NumVector <- seq(from = 20, to = 50, by = 5)
NumVector
## [1] 20 25 30 35 40 45 50
NumVector2 <- seq(20, 50, 5)
NumVector2
## [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.
quadratic <- function (a,b,c)
{
if(a == 0)
{
return ("Cannot be computed")
}
else if (is.na (sqrt(b^2 - 4*a*c) < 0 ))
{
return ("There are no real roots")
}
else if (sqrt(b^2 - 4*a*c) == 0)
{
Sol <- (-b / 2*a)
return (sprintf("Solution is %s",Sol))
}
else
{
Sol1 <- (-b + sqrt(b^2 - 4*a*c)) / (2*a)
Sol2 <- (-b - sqrt(b^2 - 4*a*c)) / (2*a)
return (sprintf("Solutions are %s, and %s",
format(round(Sol1,8), nsmall = 8),
format(round(Sol2,8), nsmall = 8)))
}
}
#Test Runs
quadratic(1,0,5)
## Warning in sqrt(b^2 - 4 * a * c): NaNs produced
## [1] "There are no real roots"
quadratic(0,1,5)
## [1] "Cannot be computed"
quadratic(2,4,2)
## [1] "Solution is -4"
quadratic(1,7,5)
## [1] "Solutions are -0.80741760, and -6.19258240"