Class: Flt::Solver::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/solver/base.rb

Direct Known Subclasses

RFSecantSolver, SecantSolver

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &blk) ⇒ Base

Admitted options:

  • :context : Numerical context (e.g. Flt::Decimal::Context) Float by default

  • :default_guesses : default initial guesses

  • :tolerance : numerical tolerance

  • :equation : equation to be solved; can also be passed as a block

default_guesses: nil for no pre-guess, or one or two guesses (use array for two)

The values of any of the parameters can also be passed as arguments (not in the options Hash, if present) in any order, e.g.:

Solver::Base.new Flt::DecNum.context, tolerance: Flt::Tolerance(3, :decimals)


23
24
25
26
27
28
29
30
31
32
# File 'lib/solver/base.rb', line 23

def initialize(*args, &blk)
  options = Base.extract_options(*args, &blk)
  @context = options[:context] || Float.context
  @default_guesses = Array(options[:default_guesses])
  @x = @default_guesses.first
  @f = options[:equation]
  @tol = options[:tolerance] # user-requested tolerance
  @max_it = 8192
  reset
end

Instance Attribute Details

#iterationObject (readonly)

Returns the value of attribute iteration.



77
78
79
# File 'lib/solver/base.rb', line 77

def iteration
  @iteration
end

#reasonObject (readonly)

Returns the value of attribute reason.



77
78
79
# File 'lib/solver/base.rb', line 77

def reason
  @reason
end

Instance Method Details

#resetObject



34
35
36
37
38
39
40
# File 'lib/solver/base.rb', line 34

def reset
  @l_x = nil
  @fx = nil
  @l_fx = nil
  @ok = true
  @conv = false
end

#root(*guesses) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/solver/base.rb', line 42

def root(*guesses)
  @guess = (guesses + @default_guesses).map{|g| num(g)}
  reset
  @l_x = @x = @guess.first
  @l_fx = @fx = eval_f(@x)
  @ok = true
  @conv = false

  # Minimum tolerance of the numeric type used
  @numeric_tol = Flt::Tolerance(1,:ulps) # Tolerance(@context.epsilon, :floating)

  raise "Invalid parameters" unless validate

  @reason = nil
  @iteration = 0
  # TODO: handle NaNs (stop or try to find other guess)
  while @ok && @iteration < @max_it
    next_x = step()
    @l_x = @x
    @l_fx = @fx
    @x = next_x
    @fx = eval_f(@x)
    @conv = test_conv() if @ok
    break if @conv
    @iteration += 1
  end
  @ok = false if @iteration >= @max_it # TODO: set reason
  @x

end

#valueObject



73
74
75
# File 'lib/solver/base.rb', line 73

def value
  @fx
end