Class: Dobjects::MathEvaluator

Inherits:
Object
  • Object
show all
Includes:
Math
Defined in:
lib/Dobjects/Dvector_extras.rb

Overview

MathEvaluator enables one to evaluate a simple mathematical expression such as “x + cos(x)”, where the array x is given at each call to compute, or “x + y**z”, or…

This class acts as a backend for Dvector.compute_formula, to make sure that the Math module is included, without the drawback of cluttering all Math functions in Dvector, which would admittedly be quite stupid.

Instance Method Summary collapse

Constructor Details

#initialize(formula, argname, mods = []) ⇒ MathEvaluator

Creates an evaluator for a formula. formula is the formula. It is transformed into a block that takes argname as an argument – argname can be whatever you want. mods are the modules you would like the formula to include. Math is included by default, but you can include other ones to make other kinds of functions available.

MathEvaluator.new("col[0] + col[1]", "col")
MathEvaluator.new("x*cos(y)", "x,y")


24
25
26
27
28
29
# File 'lib/Dobjects/Dvector_extras.rb', line 24

def initialize(formula, argname, mods = [])
  for mod in mods
    self.extend mod
  end
  @block = eval "proc { |#{argname}| #{formula} }"
end

Instance Method Details

#compute(*args) ⇒ Object

This function does the actual evaluation with the blocks given.

e = MathEvaluator.new("x*y", "x,y")
e.compute(1,2)         -> 2

If an exception arises, NaN is returned. Note that compilation problems will be caught before ;-)…



39
40
41
42
43
44
45
# File 'lib/Dobjects/Dvector_extras.rb', line 39

def compute(*args)
  begin
    return compute_unsafe(*args)
  rescue
    return 0.0/0.0
  end
end

#compute_unsafe(*args) ⇒ Object

This function does the actual evaluation with the blocks given.

e = MathEvaluator.new("x*y", "x,y")
e.compute(1,2)         -> 2

No care is taken to intercept exceptions.



54
55
56
# File 'lib/Dobjects/Dvector_extras.rb', line 54

def compute_unsafe(*args)
  return @block.call(*args)
end