Module: Ra::Quadratic

Defined in:
lib/ra/quadratic.rb

Overview

A solver for all things quadratic. Given the equation:

ax² + bx +c = 0

The solution for ‘x“ can be found via:

(-b ± √(b² - 4ac)) / (2a)

No solution is defined when the discriminant (‘b² - 4ac`) is negative or `a` is zero.

Class Method Summary collapse

Class Method Details

.solve(a:, b:, c:) ⇒ Array<Numeric>

(-b ± √(b² - 4ac)) / (2a)

Parameters:

  • a (Numeric)
  • b (Numeric)
  • c (Numeric)

Returns:

  • (Array<Numeric>)


20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ra/quadratic.rb', line 20

def self.solve(a:, b:, c:)
  return [] if a.zero?

  discriminant = (b**2) - (4 * a * c)
  return [] if discriminant.negative?

  [
    (-b - Math.sqrt(discriminant)) / (2 * a),
    (-b + Math.sqrt(discriminant)) / (2 * a),
  ]
end