Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2. (a) Write an R function quadratic which computes the real-valued solutions of

ID: 3357638 • Letter: 2

Question

2. (a) Write an R function quadratic which computes the real-valued solutions of the quadratic equation ar2 + br + c 0 Your function should take a, b, and c as arguments and should return the unique solutions to the above quadradic equation scriminant = b2-4ac. ·Your function should start with computing the di · If 0, then the quadratic equation has two solutions. length two containing both solutions and- In this case return a vector of 2a 7 marks (b) So far, your function does not handle the case a = 0 correctly. Update your function quadratic such that it returns if a-0. If a-b 0 your function should return NA. [3 marks]

Explanation / Answer

quadratic = function (a,b,c){
  
D= b^2 -4*a*c
if ( D < 0 ) sol = (numeric(0))
if ( D == 0) sol = (-b/2/a)
if ( D > 0) sol = (c((-b +sqrt(D))/2/a,(-b -sqrt(D))/2/a))
  
return(sol)
}

# This function doesn't handle the a = 0 case nicely, this updated function below does

quadratic = function (a,b,c){
  
if (sum (a == 0, b==0) == 0)
{
D= b^2 -4*a*c
if ( D < 0 ) sol = (numeric(0))
if ( D == 0) sol = (-b/2/a)
if ( D > 0) sol = (c((-b +sqrt(D))/2/a,(-b -sqrt(D))/2/a))
}
  
if ( a == 0 & b!= 0 ) sol = -c/b
if ( a == 0 & b == 0) sol = NA
  
  
return(sol)
}