# How do I write a function that will tell me if an equation has no solution?

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

{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"))
}}

``````

Perhaps this?

``````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
``````

Thanks for helping! Unfortunately, keep getting this error:

``````Warning messages:
1: In sqrt((b * b) - (4 * a * c)) : NaNs produced
2: In sqrt((b * b) - (4 * a * c)) : NaNs produced
``````

But it also prints out `"There is no solution to this quadratic equation"`

Oh!! I see that now, it does. Thank you!!

1 Like

if you anticipate warnings that you dont want to show you can use

``````# warn
sqrt(-1)
# dont warn
suppressWarnings(sqrt(-1))``````

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.