Class: Autodiff::DualNum

Inherits:
Numeric show all
Defined in:
lib/autodiff/dual_num.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Numeric

#epsilon

Constructor Details

#initialize(n, e = 0) ⇒ DualNum

Returns a new instance of DualNum.



19
20
21
22
23
# File 'lib/autodiff/dual_num.rb', line 19

def initialize(n, e=0)
  @real = n
  @epsilon = e
  self.freeze
end

Instance Attribute Details

#realObject (readonly)

Returns the value of attribute real.



18
19
20
# File 'lib/autodiff/dual_num.rb', line 18

def real
  @real
end

Instance Method Details

#*(other) ⇒ Object



45
46
47
48
49
# File 'lib/autodiff/dual_num.rb', line 45

def *(other)
  r = @real * other.real
  e = @real * other.epsilon + @epsilon * other.real
  self.class.new(r, e)
end

#**(other) ⇒ Object



59
60
61
62
63
# File 'lib/autodiff/dual_num.rb', line 59

def **(other)
  r = @real ** other.real
  e = other.real * (@real ** (other.real - 1)) * @epsilon
  self.class.new(r, e)
end

#+(other) ⇒ Object



33
34
35
36
37
# File 'lib/autodiff/dual_num.rb', line 33

def +(other)
  r = @real + other.real
  e = @epsilon + other.epsilon
  self.class.new(r, e)
end

#-(other) ⇒ Object



39
40
41
42
43
# File 'lib/autodiff/dual_num.rb', line 39

def -(other)
  r = @real - other.real
  e = @epsilon - other.epsilon
  self.class.new(r, e)
end

#/(other) ⇒ Object

do tmp = 1/other then do self * tmp



52
53
54
55
56
57
# File 'lib/autodiff/dual_num.rb', line 52

def /(other)
  r = 1.0 / other.real
  e = - other.epsilon.to_f / (other.real ** 2)
  tmp = self.class.new(r, e)
  self * tmp
end

#to_dualObject



25
26
27
# File 'lib/autodiff/dual_num.rb', line 25

def to_dual
  self
end

#to_floatObject



65
66
67
# File 'lib/autodiff/dual_num.rb', line 65

def to_float
  real
end

#to_one_epsilonObject



29
30
31
# File 'lib/autodiff/dual_num.rb', line 29

def to_one_epsilon
  Autodiff::DualNum.new(self.real, 1)
end