Interval arithmetic in Ruby

Besides making obvious a possible loss of precision during floating point calculations, interval arithmetic provides not-so-conventional methods for a variety of computational applications.

The open-source Ruby package I wrote implements an interval system in the extended real set that is closed under arithmetic operations. Correct rounding ensures that the operations are inclusion-wise monotonic.

The package documentation provides installation instructions, user's guide, and class reference.

Numerical instability

Fire up ruby’s interactive shell by typing

irb

on the command line. Take into consideration the rather innocent looking function

def f(x,y)
  (333.75-x**2)* y**6 + x**2 * (11* x**2 * y**2-121 * y**4 -2) +
    5.5 * y**8 + x/(2*y)
end

We can calculate it for some specific x and y,

f(77617.0,33096.0)          # => 1.17260394005318

There is only one problem: this result is wrong. The correct result can be obtained by calculating separately the numerator and denominator of f using integer arithmetic.

def f_num(x,y)
  ((33375- 100 * x**2)* y**6 +
    100 * x**2 * (11* x**2 * y**2-121 * y**4 -2) +
    550 * y**8) *
  2*y + 100 *x
end

def f_den(x,y)
  200*y
end

f_num(77617, 33096).to_f / f_den(77617, 33096).to_f
                            # => -0.827396059946821

The result obtained by directly calculating f is completely wrong: sign, order of magnitude, and all digits are wrong. No warnings, no errors are generated, but the computation simply yields unreliable results.

Among other interesting applications, interval arithmetic provides the possibility of detecting similar occurrences of numerical instability.