This commit is contained in:
2026-03-23 17:15:42 +03:00
parent 9642c92eec
commit 1c6c2b24ff

View File

@@ -20,6 +20,12 @@ module RubyAlgebra
def diff(v)
raise NotImplementedError, "#{self.class}#diff not implemented"
end
def evaluate
raise NotImplementedError, "#{self.class}#evaluate not implemented"
end
def constant?
raise NotImplementedError, "#{self.class}#constant? not implemented"
end
end
class Addition < Expression
@@ -59,6 +65,15 @@ module RubyAlgebra
def diff(v)
Addition.new(@lhs.diff(v), @rhs.diff(v))
end
def evaluate
lhs_val = @lhs.evaluate
rhs_val = @rhs.evaluate
return nil if lhs_val.nil? || rhs_val.nil?
lhs_val + rhs_val
end
def constant?
@lhs.constant? && @rhs.constant?
end
end
class Subtraction < Addition
@@ -79,6 +94,15 @@ module RubyAlgebra
def diff(v)
Subtraction.new(@lhs.diff(v), @rhs.diff(v))
end
def evaluate
lhs_val = @lhs.evaluate
rhs_val = @rhs.evaluate
return nil if lhs_val.nil? || rhs_val.nil?
lhs_val - rhs_val
end
def constant?
@lhs.constant? && @rhs.constant?
end
end
class Multiplication < Expression
@@ -134,6 +158,15 @@ module RubyAlgebra
term2 = Multiplication.new(@lhs, v_prime)
Addition.new(term1, term2)
end
def evaluate
lhs_val = @lhs.evaluate
rhs_val = @rhs.evaluate
return nil if lhs_val.nil? || rhs_val.nil?
lhs_val * rhs_val
end
def constant?
@lhs.constant? && @rhs.constant?
end
end
class Division < Multiplication
@@ -159,6 +192,16 @@ module RubyAlgebra
denominator = Power.new(@rhs, Constant.new(2))
Division.new(numerator, denominator)
end
def evaluate
lhs_val = @lhs.evaluate
rhs_val = @rhs.evaluate
return nil if lhs_val.nil? || rhs_val.nil?
return nil if rhs_val == 0
lhs_val / rhs_val
end
def constant?
@lhs.constant? && @rhs.constant?
end
end
class Power < Expression
@@ -207,6 +250,15 @@ module RubyAlgebra
coeff = Constant.new(n)
Multiplication.new(coeff, Multiplication.new(new_power, base_diff))
end
def evaluate
base_val = @base.evaluate
exp_val = @exponent.evaluate
return nil if base_val.nil? || exp_val.nil?
base_val ** exp_val
end
def constant?
@base.constant? && @exponent.constant?
end
end
class Constant < Expression
@@ -240,6 +292,12 @@ module RubyAlgebra
def diff(v)
Constant.new(0)
end
def evaluate
@value
end
def constant?
true
end
end
class Variable < Expression
@@ -278,5 +336,11 @@ module RubyAlgebra
def diff(v)
@symbol == v ? Constant.new(1) : Constant.new(0)
end
def evaluate
nil
end
def constant?
false
end
end
end