a*(x^2) + b*x +c equation in r

2.8k views Asked by At

I've been given this equation, and I'm asked to create a program where the solutions for

a*(x^2) + b*x +c = 0

are given like this:

1) if D > 0, 2 solutions are:

x1 = (-b -sqrt(D))/2a and x2= (-b+ sqrt(D))/2a

2)if D = 0 , 1 'double' solution':

x1 = -b/2a

3)if D < 0, no true solution

where D the linear discriminant = b^2 - 4*a*

I have absolutely no idea in what to try, the only thing i did was try to define D:

 `D <- b^2 - 4*a*c`

But i get an error

Error: object 'b' not found.

Any help would be greatly appreciated.

1

There are 1 answers

4
S.C On BEST ANSWER

This will work:

# calculate the real root(s) of a quadratic polynomial
# coefficients of which are given as aa, bb and cc
quadratic_roots <- function(aa = 1, bb = 2, cc = 1)
{
    # calculate the discriminant
    disc <- bb^2 - 4 * aa * cc

    if (disc == 0) # if1, single root
    {
        return(-bb / (2 * aa))
    }   
    else
    {
        if (disc > 0) # if2, two roots
        {
            root1 <- (-bb - sqrt(disc)) / (2 * aa)
            root2 <- (-bb + sqrt(disc)) / (2 * aa)
            return(c(root1, root2))

        }
        else # no real roots, return NA
        {
            return(NA)
        }   
    }   
}

Note that r-base has a built-in polyroot, however it will automatically return complex roots so will not serve your purpose.

And why I used aa, bb and cc instead of a, b and c:

Because "c" coincides with a very important built in function. It is not good practice to use built-in function names for custom object names.