Files
RubyAlgebra/spec/expression_spec.rb
2026-04-13 21:05:59 +03:00

83 lines
3.2 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

require 'rspec'
require_relative '../lib/ruby_algebra/polynomial'
require_relative '../lib/ruby_algebra/parser'
RSpec.describe "RubyAlgebra Extended Suite" do
let(:x) { RubyAlgebra::Polynomial.new([RubyAlgebra::Term.new(1, { "x" => 1 })]) }
let(:y) { RubyAlgebra::Polynomial.new([RubyAlgebra::Term.new(1, { "y" => 1 })]) }
describe "Математические крайности (Edge Cases)" do
it "умножение на ноль дает пустой многочлен (0)" do
zero = RubyAlgebra::Polynomial.new([RubyAlgebra::Term.new(0)])
result = x * zero
expect(result.terms.reject { |t| t.coeff == 0 }).to be_empty
end
it "возведение в степень через умножение (x * x * x = x^3)" do
result = x * x * x
expect(result.terms.first.variables["x"]).to eq 3
expect(result.terms.first.coeff).to eq 1
end
it "сложение противоположных значений (x + (-x) = 0)" do
minus_x = x * -1
result = x + minus_x
expect(result.terms.reject { |t| t.coeff == 0 }).to be_empty
end
end
describe "Дифференцирование (Продвинутое)" do
it "производная от константы всегда 0" do
expr = RubyAlgebra::Polynomial.new([RubyAlgebra::Term.new(999)])
expect(expr.diff("x").terms.all? { |t| t.coeff == 0 }).to be true
end
it "вторая производная: diff(x^2) -> 2x, diff(2x) -> 2" do
first_der = (x * x).diff("x")
second_der = first_der.diff("x")
expect(second_der.terms.first.coeff).to eq 2
expect(second_der.terms.first.variables).to be_empty
end
it "частная производная: diff(x*y, 'x') -> y" do
expr = x * y
derivative = expr.diff("x")
expect(derivative.terms.first.variables).to eq({ "y" => 1 })
expect(derivative.terms.first.variables).not_to have_key("x")
end
end
describe "Подстановка (Substitution)" do
it "подстановка в многочлен с двумя переменными (x + y where x=1, y=2)" do
expr = x + y
# substitute принимает хеш значений
result = expr.substitute({ "x" => 1, "y" => 2 })
# Должно получиться 3 (константа)
expect(result.terms.first.coeff).to eq 3
expect(result.terms.first.variables).to be_empty
end
it "частичная подстановка (x*y where x=2) -> 2y" do
expr = x * y
result = expr.substitute({ "x" => 2 })
expect(result.terms.first.coeff).to eq 2
expect(result.terms.first.variables).to eq({ "y" => 1 })
end
end
describe "Строковое представление (to_s)" do
it "корректно отображает отрицательные коэффициенты" do
expr = x - 5
expect(expr.to_s).to eq "x - 5"
end
it "не пишет '1' перед переменной (x вместо 1x)" do
expect(x.to_s).to eq "x"
end
it "выводит '0', если многочлен пуст" do
zero_poly = RubyAlgebra::Polynomial.new([])
expect(zero_poly.to_s).to eq "0"
end
end
end