good-code ex 1: removing repeats, solving quadratics

Hopefully as a teenager you learnt that quadratic equations, a * x ^2 + b * x + c = 0, have two complex solutions, and that there is a formula to calculate them. This R function calculates those solutions.

x1 <- (-b + sqrt(as.complex(b ^ 2 - 4 * a * c))) / (2 * a)
x2 <- (-b - sqrt(as.complex(b ^ 2 - 4 * a * c))) / (2 * a)
solutions <- c(x1, x2)

Update the code block to remove repeated code

Vectorization of operators helps here. I also think it is clearer if you break it into two lines.

discriminant <- sqrt(as.complex(b ^ 2 - 4 * a * c))
(-b + c(-1, 1) * discriminant) / (2 * a)

To make the code reusable, wrap the code you just wrote into a function named solve_quadratic. The function should have three inputs: a, b, and c, and it should return a vector of two complex numbers.

# your solve_quadratic function
solve_quadratic <- function(a, b, c)
{
  discriminant <- sqrt(as.complex(b ^ 2 - 4 * a * c))
  (-b + c(-1, 1) * discriminant) / (2 * a)
}

Now make sure that your function works, by writing some unit tests for it.

# unit tests
test_that(
  "solve_quadratic, with inputs 1, -5, 6, returns 2, 3",
  {
    expected <- c(2, 3) + 0i
    actual <- solve_quadratic(1, -5, 6)
    expect_equal(actual, expected)
  }
)
# etc.

.