-2

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.

Serhat Cevikel
  • 720
  • 3
  • 11
gkal
  • 3
  • 1
  • 3

1 Answers1

0

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.

Serhat Cevikel
  • 720
  • 3
  • 11
  • Thanks a lot, that was really helpful! I have a couple of questions though, is it not supposed to show c(root1,root2) when i run disc>0 ? When I do that it returns : Error: object 'disc' not found and when i run : disc <- bb^2 - 4 * aa * cc it gives : Error: object 'bb' not found (also, what do the numbers given to aa,bb,cc mean? i know i may be asking some obvious stuff but its the first time i actually experiment with r an programming) – gkal Dec 03 '17 at 15:13
  • 'disc' is not an argument of thfunstion described in the answer. You have to provide values for 'aa', 'bb' and 'cc'. – Bhas Dec 03 '17 at 15:23
  • and how do i do that, i mean they are supposed to be numbers in the actual equation, how do i value them? – gkal Dec 03 '17 at 15:29
  • It is better for you to view the "Writing Your Own Functions" section of "An Introduction to R" manual at https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Writing-your-own-functions – Serhat Cevikel Dec 03 '17 at 15:38