Module: Xirr::Native

Defined in:
ext/xirr/xirr_native.c

Class Method Summary collapse

Class Method Details

.rtsafe(flows, guess, tol, max_iter) ⇒ Object

Xirr::Native.rtsafe(flows, guess, tolerance, max_iterations) -> Float | nil



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'ext/xirr/xirr_native.c', line 94

static VALUE rb_rtsafe(VALUE self, VALUE flows, VALUE guess, VALUE tol, VALUE max_iter) {
    long n, i;
    double *t, *amt, rate;
    /* ALLOCV buffers are freed by the GC even if a conversion below raises, so a
       bad element can't leak them. */
    VALUE t_buf, amt_buf;

    Check_Type(flows, T_ARRAY);
    n = RARRAY_LEN(flows);
    t = ALLOCV_N(double, t_buf, n);
    amt = ALLOCV_N(double, amt_buf, n);

    for (i = 0; i < n; i++) {
        VALUE pair = rb_ary_entry(flows, i);
        Check_Type(pair, T_ARRAY);
        t[i] = NUM2DBL(rb_ary_entry(pair, 0));
        amt[i] = NUM2DBL(rb_ary_entry(pair, 1));
    }

    rate = rtsafe(n, t, amt, NUM2DBL(guess), NUM2DBL(tol), NUM2LONG(max_iter));
    ALLOCV_END(t_buf);
    ALLOCV_END(amt_buf);

    if (isnan(rate) || isinf(rate) || rate <= -1.0) return Qnil;
    return DBL2NUM(rate);
}