Write code to do the task once
Modify code to make it more abstract
Wrap it in a function – define the function name and parameters
Add error handling - check inputs, necessary conditions
# Assume we have an equation ax^2 + bx + c = 0
# Solve for x
# Defined outside -- make more readable names
x2coeff = 1
xcoeff = 5
intcoeff = 2
## Extra parameter
under_sqrt = xcoeff^2-4*x2coeff*intcoeff
# need to check if under_sqrt is nonnegative
if (under_sqrt < 0) {
print("Determinant is negative. Zeros will be imaginary.")
}
x1 = (-xcoeff + sqrt(under_sqrt))/(2*x2coeff)
x2 = (-xcoeff - sqrt(under_sqrt))/(2*x2coeff)
c(x1, x2)
[1] -0.4384472 -4.5615528
# Assume we have an equation ax^2 + bx + c = 0
# Solve for x
quad_formula <- function(x2coeff, xcoeff, intcoeff) {
## Extra parameter
under_sqrt = xcoeff^2-4*x2coeff*intcoeff
# need to check if under_sqrt is nonnegative
if (under_sqrt < 0) {
print("Determinant is negative. Zeros will be imaginary.")
}
x1 = (-xcoeff + sqrt(under_sqrt))/(2*x2coeff)
x2 = (-xcoeff - sqrt(under_sqrt))/(2*x2coeff)
return(c(x1, x2))
}
# Test the function
quad_formula(1, 5, 2)
[1] -0.4384472 -4.5615528
[1] -0.4384472 -4.5615528
# Assume we have an equation ax^2 + bx + c = 0
# Solve for x
quad_formula <- function(x2coeff, xcoeff, intcoeff) {
# Ensure parameters are numeric before doing math with them
stopifnot(is.numeric(x2coeff) & is.numeric(xcoeff) & is.numeric(intcoeff))
## Extra parameter
under_sqrt = xcoeff^2-4*x2coeff*intcoeff
# need to check if under_sqrt is nonnegative
if (under_sqrt < 0) {
print("Determinant is negative. Zeros will be imaginary.")
}
x1 = (-xcoeff + sqrt(under_sqrt))/(2*x2coeff)
x2 = (-xcoeff - sqrt(under_sqrt))/(2*x2coeff)
return(c(x1, x2))
}
# Test the function
quad_formula(1, 5, 2)
[1] -0.4384472 -4.5615528
[1] -0.4384472 -4.5615528
Error in quad_formula("A", "B", "C"): is.numeric(x2coeff) & is.numeric(xcoeff) & is.numeric(intcoeff) is not TRUE