add substitution and differentiation

This commit is contained in:
2026-04-13 19:58:40 +03:00
parent 1fff529e83
commit 037c34b38e
3 changed files with 31 additions and 12 deletions

View File

@@ -50,7 +50,7 @@ module RubyAlgebra
@locals[command.lhs] = result @locals[command.lhs] = result
return "#{command.lhs} = #{result}" return "#{command.lhs} = #{result}"
when :subs when :subs
result = operand1.evaluate(operand2) result = operand1.substitute(operand2)
@locals[command.lhs] = result @locals[command.lhs] = result
return "#{command.lhs} = #{result}" return "#{command.lhs} = #{result}"
end end

View File

@@ -261,10 +261,17 @@ module RubyAlgebra
raise ParserError, "unexpected token #{n.type}, expected =" raise ParserError, "unexpected token #{n.type}, expected ="
end end
n = tokenizer.next_token n = tokenizer.next_token
unless n.type == :num || n.type == :plus || n.type == :minus
raise ParserError, "unexpected token #{n.type}, expected -, + or number"
end
if n.type == :plus || n.type == :minus
negative = true if n.type == :minus
n = tokenizer.next_token
end
unless n.type == :num unless n.type == :num
raise ParserError, "unexpected token #{n.type}, expected number" raise ParserError, "unexpected token #{n.type}, expected number"
end end
substitutions[variable] = n.value substitutions[variable] = if negative then -n.value else n.value end
end end
n = tokenizer.next_token n = tokenizer.next_token
unless n.type == :paren && n.closing == true unless n.type == :paren && n.closing == true

View File

@@ -33,16 +33,12 @@ module RubyAlgebra
result result
end end
def diff def diff(variable)
raise NotImplementedError Polynomial.new(@terms.map { |term| term.diff(variable) })
end end
def substitute(values) def substitute(values)
result = 0 Polynomial.new(@terms.map { |term| term.substitute(values) })
@terms.each do |term|
# ...
end
result
end end
def +(other) def +(other)
@@ -190,12 +186,28 @@ module RubyAlgebra
end end
end end
def diff(var) def diff(variable)
raise NotImplementedError return Term.new if @variables[variable].nil?
new_coeff = @coeff
new_variables = @variables.filter { |var, power| var != variable }
unless @variables[variable] == 1
new_coeff *= @variables[variable]
new_variables[variable] = @variables[variable] - 1
end
Term.new(new_coeff, new_variables)
end end
def substitute(values) def substitute(values)
raise NotImplementedError new_coeff = @coeff
new_variables = {}
@variables.each do |var, pow|
if values[var].nil?
new_variables[var] = pow
else
new_coeff *= values[var] ** pow
end
end
Term.new(new_coeff, new_variables)
end end
def +(other) def +(other)