Hello Numba community.
I’m trying to use the guvectorize
decorator to make gufuncs out of some of my functions in NumPy-Financial. Currently, what I have is as follows:
@numba.guvectorize("(),(n)->()")
def _npv_internal(r, values, res):
acc = 0.0
for t in range(values.shape[0]):
acc += values[t] / ((1.0 + r) ** t)
res[0] = acc
This is called as follows:
r = np.atleast_1d(rate)
v = np.atleast_2d(values)
res = np.empty(shape=(r.shape[0], v.shape[0]))
_npv_internal(r, v, res)
This passes two of my existing unit tests. However, it fails when I try adding a new test:
def test_npv_broadcast_equals_for_loop(self):
cashflows = [
[-15000, 1500, 2500, 3500, 4500, 6000],
[-25000, 1500, 2500, 3500, 4500, 6000],
[-35000, 1500, 2500, 3500, 4500, 6000],
[-45000, 1500, 2500, 3500, 4500, 6000],
]
rates = [-0.05, 0.00, 0.05, 0.10, 0.15]
res = np.empty((len(rates), len(cashflows)))
for i, r in enumerate(rates):
for j, cf in enumerate(cashflows):
res[i, j] = npf.npv(r, cf)
assert assert_allclose(npf.npv(rates, cashflows), res)
This gives the error: ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (5,)->(5) (4,6)->(4) (5,4)->(5,4) and requested shape ()
I’m not sure if there is a neat way of running this to vectorize my operations.
Could someone please help me?