This lab report was developed for the Software Design and Architecture course (Tc3003), at the Tecnológico de Monterrey, Campus Estado de México.
1. Introduction
The roots of a quadratic equation ax2 + bx + c = 0 can be computed using the quadratic formula, which is something you typically learn in high school:
INTERESTING NOTE
The quadratic formula is known in Mexico as “el chicharronero”, because even the guy who sells chicharrones (pork cracklings) knows how to use it. |
In this lab report, I will demonstrate how to determine the number of real roots of a quadratic equation in the Ruby programming language [Ruby]. Section 2 consists of the code, section 3 discusses my testing, and lastly there are some concluding remarks.
2. Number of Real Roots of a Quadratic Equation
In this part of the lab, I designed a function to compute how many real roots a quadratic equation has. This can be determined by computing the discriminant of the equation and then testing that discriminant [Baldor]. I broke the problem into those two parts:
# How many real roots does ax^2+bx+c=0 have?
def num_real_roots(a, b, c)
num_real_roots_from_discriminant(discriminant(a, b, c))
end
The two auxiliary routines used by the above code straightforwardly reflect my memories from high school:
def discriminant(a, b, c)
b ** 2 - 4 * a * c
end
def num_real_roots_from_discriminant(d)
if d < 0
0
elsif d == 0
1
else
2
end
end
3. Testing
I tested the number of real-roots function using one simple example falling into each of the three cases. Note that I took care to use examples in which the three arguments were different from one another, to improve the chances of catching certain bugs. My function worked in all three cases, as shown below:
Expression | Result |
---|---|
num_real_roots(1, 2, 3) |
0 |
num_real_roots(1, 10, 2) |
2 |
num_real_roots(2, 16, 32) |
1 |
4. Conclusion
It’s a common perception that “useful” programs have to be long. Determining the number of real roots of a quadratic equation is an example of an unusual category of computations: those that are complex enough to be worth automating, yet involve only a fixed amount of computation. As this lab demonstrated, programs which mirror routine mathematical calculations are quite straightforward to write.
5. Acknowledgements
I would like to thank my good friend Thursday Rubinstein for his advice on how to write cool Ruby method names.
6. References
-
[Baldor] J. Aureliano Baldor. Álgebra. Grupo Patria Cultural. Mexico, 2007. p. 265.
-
[Ruby] The Ruby community. Ruby Programming Language http://www.ruby-lang.org/en/ (Accessed January 22, 2013).