Class: Power

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

Overview

Implements the power operation in SymCalc

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Equation

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

Constructor Details

#initialize(base, power) ⇒ Power

Returns a new instance of Power.



607
608
609
610
# File 'lib/symcalc.rb', line 607

def initialize base, power
  @base = base
  @power = power
end

Instance Attribute Details

#baseObject

Returns the value of attribute base.



605
606
607
# File 'lib/symcalc.rb', line 605

def base
  @base
end

#powerObject

Returns the value of attribute power.



605
606
607
# File 'lib/symcalc.rb', line 605

def power
  @power
end

Instance Method Details

#==(eq) ⇒ Object



625
626
627
628
629
630
631
632
633
# File 'lib/symcalc.rb', line 625

def == eq
  if eq.is_a? Power
    return (eq.base == @base) && (eq.power == @power)
  elsif (eq == EquationValue.new(1))
    return @power == 0
  else
    return false
  end
end

#__derivative__(variable: nil) ⇒ Object



620
621
622
623
# File 'lib/symcalc.rb', line 620

def __derivative__ variable: nil
  # exp(@power * ln(@base)).derivative
  return @base ** @power * (@power.derivative(variable: variable)*Ln.new(@base) + @base.derivative(variable: variable)*@power/@base)
end

#__eval__(var_hash) ⇒ Object



616
617
618
# File 'lib/symcalc.rb', line 616

def __eval__ var_hash
  return @base.eval(var_hash) ** @power.eval(var_hash)
end

#__get_m_elements__(var_hash) ⇒ Object



635
636
637
638
639
640
641
642
643
644
645
# File 'lib/symcalc.rb', line 635

def __get_m_elements__ var_hash
  elms = @base.__get_m_elements__({})
  elms.each do |k, v|
    if var_hash.keys.include? k
      var_hash[k] += v * @power
    else
      var_hash[k] = @power
    end
  end
  return var_hash
end

#__simplify__Object



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/symcalc.rb', line 647

def __simplify__
  
  base = @base.simplify
  power = @power.simplify
  
  if power == EquationValue.new(0)
    return EquationValue.new(1)
  elsif power == EquationValue.new(1)
    return base
  elsif base.is_a?(EquationValue) && power.is_a?(EquationValue)
    computed = base.value ** power.value
    if computed.to_s.size <= 6
      return to_equation(computed)
    else
      return base ** power
    end
  else
    return base ** power
  end
  
end

#all_variablesObject



669
670
671
# File 'lib/symcalc.rb', line 669

def all_variables
  return (@base.all_variables + @power.all_variables).uniq
end

#displayObject



612
613
614
# File 'lib/symcalc.rb', line 612

def display
  return "(#{@base.display})^(#{@power.display})"
end