class Dobjects::MathEvaluator

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 Dobjects::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.

Public Class Methods

new(formula, argname, mods = []) click to toggle source

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")
# 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

Public Instance Methods

compute(*args) click to toggle source

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 ;-)…

# 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) click to toggle source

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.

# File lib/Dobjects/Dvector_extras.rb, line 54
def compute_unsafe(*args)
  return @block.call(*args)
end