For a homework assignment, I am tasked with writing a function in R that will return the solution, along with an explanation. It must be able to return the answer "There is no solution to this quadratic equation" when there is no solution, but I am having a hard time figuring out that part. My function works fine when there is 1 solution or 2 solutions, but when I give inputs that have no solution, I get this message:
Warning messages:
1: In sqrt((b * b) - (4 * a * c)) : NaNs produced
2: In sqrt((b * b) - (4 * a * c)) : NaNs produced
The example below should have no solution.
# Write a function to solve the quadratic formula that returns specific outputs
# depending on there being one, two, or zero solutions
quadratic.function <- function(a, b, c)
{solution1 = (-b-sqrt((b*b)-(4*a*c)))/(2*a)
solution2 = (-b+sqrt((b*b)-(4*a*c)))/(2*a)
if (solution1 == solution2){
return(list("there is only one solution", solution1))
}else if(solution1 != solution2){
return(list("there are two solutions", solution1, solution2))
}else {
return(list("There is no solution to this quadratic equation"))
}}
quadratic.function(2, 2, 3)
quadratic.function <- function(a, b, c){
solution1 = (-b-sqrt((b*b)-(4*a*c)))/(2*a)
solution2 = (-b+sqrt((b*b)-(4*a*c)))/(2*a)
if(is.na(solution1) & is.na(solution2)){
# if no solutions
return(list("There is no solution to this quadratic equation"))
} else {
# if solutions
if (solution1 == solution2){
return(list("there is only one solution", solution1))
} else if (solution1 != solution2){
return(list("there are two solutions", solution1, solution2))
}
}
}
# test
quadratic.function(1, 2, 1) # one solution
quadratic.function(2, 1, -30) # two solutions
quadratic.function(2, 2, 3) # no solutions