require_relative 'test_helper' class TestPolynomial < MiniTest::Unit::TestCase def test_to_s polynomial = Polynomial.parse('5x + 2x^2 + 20') assert_equal '+ 2.0 x^2 + 5.0 x + 20.0', polynomial.to_s end def test_derivative_of_linear_functions polynomial = Polynomial.parse('5x + 2') assert_equal Polynomial.parse('5') ,polynomial.derivative end def test_derivative_functions_with_higher_degree polynomial = Polynomial.parse('5.5x^4 + 3.5x^3 + 2x^2 + 2x + 50') assert_equal Polynomial.parse('22x^3 + 10.5x^2 + 4x + 2'), polynomial.derivative end def test_calculation polynomial = Polynomial.parse('2x^4 - 1 x') assert_equal 1245, polynomial.calculate(5) end def test_parsing assert_equal 0, Polynomial.parse('2').terms.values.first.exponent assert_equal 2, Polynomial.parse('2').terms.values.first.coefficient terms = Polynomial.parse('2x^2 + 5.5x^1 - 20').terms.values.sort_by(&:exponent).reverse assert_equal [2,1,0], terms.map(&:exponent) assert_equal [2,5.5,-20], terms.map(&:coefficient) end def test_equality assert_equal Polynomial.parse('3x^1 + 5'), Polynomial.parse('3x + 5 x^0') end def test_degree assert_equal 5,Polynomial.parse('3x^5 - 5 x + 3').degree end def test_extrema polynomial = Polynomial.parse('3x^2 + 2x + 1') assert_equal({ min: Set[-2.0/6.0] }, polynomial.local_extrema) polynomial = Polynomial.parse('5x^3 - 5x^2 + 2x - 2') end def test_extrema_with_slope_of_derivative_equal_to_zero polynomial = Polynomial.parse('1x^4') assert_equal({ min: Set[0.0] }, polynomial.local_extrema) assert_equal({ max: Set[1.0/0, -1.0/0], min: Set[0.0]}, polynomial.extrema) end def test_no_local_extrema polynomial = Polynomial.parse('6x^6 - 5x + 50') assert_equal({}, polynomial.local_extrema) assert_equal({max: Set[ -1.0/0, 1.0/0 ]}, polynomial.extrema) end def test_no_inflection_points polynomial = Polynomial.parse('1 x^4') assert_equal({ left: Set[-1.0/0..+1.0/0] }, polynomial.curvature_behaviour) polynomial = Polynomial.parse('-1 x^4') assert_equal({ right: Set[-1.0/0..+1.0/0] }, polynomial.curvature_behaviour) polynomial = Polynomial.parse('5x^2') assert_equal({ left: Set[-1.0/0..+1.0/0] }, polynomial.curvature_behaviour) end def test_no_extremums polynomial = Polynomial.parse('5') assert_equal({}, polynomial.extrema) end def test_no_curve_and_no_inflection_points polynomials = [] polynomials << Polynomial.parse('5 x + 4') polynomials << Polynomial.parse('4') polynomials.each do |polynomial| assert_equal({}, polynomial.curvature_behaviour) end end def test_two_inflection_points polynomial = Polynomial.parse('+ 1.0 x^4 + 5.0 x^3 - 1.0 x^2 + 3.0 x + 5.0') assert_equal({left:Set[-1.0/0..-2.5649778198, 0.0649778198..1.0/0], right: Set[-2.5649778198..0.0649778198] } , polynomial.curvature_behaviour) end end