Class: Variable

Inherits:
Equation show all
Defined in:
lib/symcalc.rb

Overview

Implements the Variable class

Instance Method Summary collapse

Methods inherited from Equation

#*, #**, #+, #-, #/, #__simplify__, #coerce, #derivative, #eval, #inspect, #simplify, #to_s

Constructor Details

#initialize(name, fixed_value = nil) ⇒ Variable

Create a new symbolic variable with a custom display name, and an optional fixed value Accepts the display name and an optional fixed_value Fixed_value works in the cases of evaluating the function

Example: x = Variable.new “x”, 5 fx = x ** 2 fx.eval # => 25



287
288
289
290
# File 'lib/symcalc.rb', line 287

def initialize name, fixed_value = nil
	@name = name
	@fixed_value = fixed_value
end

Instance Method Details

#__derivative__(variable: nil) ⇒ Object



308
309
310
311
312
313
314
# File 'lib/symcalc.rb', line 308

def __derivative__ variable: nil
	if variable == nil || variable == self
		return EquationValue.new 1
	else
		return to_equation(0)
	end
end

#__eval__(var_hash) ⇒ Object



297
298
299
300
301
302
303
304
305
306
# File 'lib/symcalc.rb', line 297

def __eval__ var_hash
	if @fixed_value
		return @fixed_value
	elsif var_hash.keys.include?(@name.to_sym) or var_hash.keys.include?(@name.to_s)
		return (var_hash[@name.to_sym] or var_hash[@name.to_s])
	else
		raise "No value provided for #{@name.to_s} in eval"
		# return nil
	end
end

#__get_m_elements__(var_hash) ⇒ Object



316
317
318
319
320
321
322
323
# File 'lib/symcalc.rb', line 316

def __get_m_elements__ var_hash
	if var_hash.keys.include? self
		var_hash[self] += 1
	else
		var_hash[self] = 1
	end
	return var_hash
end

#all_variablesObject



325
326
327
# File 'lib/symcalc.rb', line 325

def all_variables
	return [self]
end

#displayObject



292
293
294
# File 'lib/symcalc.rb', line 292

def display
	return @name
end