Skip to content

Commit e78a1fc

Browse files
committed
feat: add time free kinematic equation solver
Fixes: #193
1 parent bda11bd commit e78a1fc

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

maths/time_free_equation.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
# Solves forms of the kinematic equation:
4+
# vf^2 - vi^2 = 2 * a * delta_x
5+
class TimeFreeEquation
6+
class << self
7+
def displacement(initial_velocity:, final_velocity:, acceleration:)
8+
raise ZeroDivisionError, 'acceleration cannot be zero' if acceleration.zero?
9+
10+
((final_velocity**2) - (initial_velocity**2)) / (2.0 * acceleration)
11+
end
12+
13+
def acceleration(initial_velocity:, final_velocity:, displacement:)
14+
raise ZeroDivisionError, 'displacement cannot be zero' if displacement.zero?
15+
16+
((final_velocity**2) - (initial_velocity**2)) / (2.0 * displacement)
17+
end
18+
19+
def final_velocity(initial_velocity:, acceleration:, displacement:)
20+
value = (initial_velocity**2) + (2.0 * acceleration * displacement)
21+
raise DomainError, 'final velocity is not real for the provided inputs' if value.negative?
22+
23+
Math.sqrt(value)
24+
end
25+
26+
def initial_velocity(final_velocity:, acceleration:, displacement:)
27+
value = (final_velocity**2) - (2.0 * acceleration * displacement)
28+
raise DomainError, 'initial velocity is not real for the provided inputs' if value.negative?
29+
30+
Math.sqrt(value)
31+
end
32+
end
33+
end
34+
35+
class DomainError < StandardError; end

maths/time_free_equation_test.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# frozen_string_literal: true
2+
3+
require 'minitest/autorun'
4+
require_relative './time_free_equation'
5+
6+
class TimeFreeEquationTest < Minitest::Test
7+
def test_displacement
8+
assert_in_delta 24.0,
9+
TimeFreeEquation.displacement(initial_velocity: 2.0, final_velocity: 10.0, acceleration: 2.0),
10+
1E-12
11+
end
12+
13+
def test_acceleration
14+
assert_in_delta 3.0,
15+
TimeFreeEquation.acceleration(initial_velocity: 4.0, final_velocity: 10.0, displacement: 14.0),
16+
1E-12
17+
end
18+
19+
def test_final_velocity
20+
assert_in_delta 13.0,
21+
TimeFreeEquation.final_velocity(initial_velocity: 5.0, acceleration: 3.0, displacement: 24.0),
22+
1E-12
23+
end
24+
25+
def test_initial_velocity
26+
assert_in_delta 6.0,
27+
TimeFreeEquation.initial_velocity(final_velocity: 14.0, acceleration: 4.0, displacement: 20.0),
28+
1E-12
29+
end
30+
31+
def test_domain_error_for_imaginary_velocity
32+
assert_raises DomainError do
33+
TimeFreeEquation.final_velocity(initial_velocity: 1.0, acceleration: -10.0, displacement: 1.0)
34+
end
35+
end
36+
end

0 commit comments

Comments
 (0)