Usage of parallel option in numba.jit decoratior makes function give wrong result

旧街凉风 提交于 2019-12-06 09:20:00

The problem with parallel=True is that it's a black-box. Numba doesn't even guarantee that it will actually parallelize anything. It uses heuristics to find out if it's parallelizable and what could be done in parallel. These can fail and in your example they do fail, just like in my experiments with parallel and numba. That makes parallel untrustworthy and I would advise against using it!

In newer versions (0.34) prange was added an you could have more luck with that. It can't be applied in this case because prange works like range and that's different from np.linspace...

Just a note: You can avoid building z and doing the np.where in your function completely, you could just do the checks explicitly:

import numpy as np
import numba as nb

@nb.njit   # equivalent to "jit(nopython=True)".
def func_2(x1,y1,x2,y2,r1,r2,n):
    x_ = np.linspace(x1,x2,n)
    y_ = np.linspace(y1,y2,n)
    cnts = 0
    for i in range(n):
        for j in range(n):
            z = np.sqrt(x_[i] * x_[i] + y_[j] * y_[j])
            if r1 < z < r2:
                cnts += 1
    fill_factor = cnts/(n*n)
    return fill_factor

That should also provide some speedup compared to your function, maybe even more than using parallel=True (if it would work correctly).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!