Skip to content

Instantly share code, notes, and snippets.

@otofu-square
Last active March 6, 2017 16:04
Show Gist options
  • Save otofu-square/5fcc626ab19f620c24db53d0165cc1a6 to your computer and use it in GitHub Desktop.
Save otofu-square/5fcc626ab19f620c24db53d0165cc1a6 to your computer and use it in GitHub Desktop.
Quadratic Equations
class QuadraticEquation
attr_reader :x
def initialize(a:, b:, c:)
@a = a.to_f
@b = b.to_f
@c = c.to_f
@x = result
end
def to_s
a_str = @a != 1.0 ? "(#{@a})" : ''
b_str = @b != 1.0 ? "(#{@b})" : ''
c_str = "(#{@c})"
x_str = x.join(', ')
"formula: #{a_str}x^2 + #{b_str}x + #{c_str} = 0, x = (#{x_str})"
end
private
def result
x1, x2 = positive_x, negative_x
if x1 == x2
return [x1]
else
return [x1, x2]
end
end
def positive_x
(-@b + root(d)) / (2 * @a)
end
def negative_x
(-@b - root(d)) / (2 * @a)
end
def d
(@b ** 2) - (4 * @a * @c)
end
def root(x)
x.to_f ** (1.0 / 2.0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment