Write an R function that takes three input values which would be three coefficients,
solves quadratic equations, and prints both roots.
If the roots are the same, print the root only once. # If there are no real roots, print the message "There are no real roots."
For information of the quadratic equations, here is the Wiki page link
https://en.wikipedia.org/wiki/Quadratic_equation
Your code below
Then call the function you've just created and input the
coefficients for
the equations 3x^2 +5x + 9, x^2 -3x + 2, and x^2 +2x +1.
Your code below
I will give the code and the screenshot of the output of your example given,
result <- function(a,b,c)
{
if(discriminant(a,b,c) > 0)
{
# first case D>0
x_1 = (-b+sqrt(discriminant(a,b,c)))/(2*a)
x_2 = (-b-sqrt(discriminant(a,b,c)))/(2*a)
result = c(x_1,x_2)
}
else if(discriminant(a,b,c) == 0)
{
# second case D=0
x = -b/(2*a)
}
else
{
# third case D<0
"There are no real roots."
}
}
discriminant<-function(a,b,c)
{
# Calculate the discriminant
b^2-4*a*c
}
print("First equation : ")
print(result(3,5,9))
print("Second equation : ")
print(result(1,-3,2))
print("Third equation : ")
print(result(1,2,1))
Get Answers For Free
Most questions answered within 1 hours.