Running a Jupyter notebook in VSCode, I am getting bizarre behavior with the Cython unprotected division directive. Starting the session with %load_ext cython, run:
%%cython
import math
cimport cython
@cython.cdivision(True)
def simpleTest(int d):
cdef double c = 1/math.exp(math.log(math.sqrt(2/d)))
return c
Now run simpleTest(x) and for any value of x >= 3 I get:
ValueError: math domain error
But running without the @cython.cdivision(True) directive it works fine for all x > 0, as it should. Why does the directive break this calculation? Is there a better approach?
>Solution :
You are telling Cython to divide like in C. In C, integer division produces integer results, rounding toward 0.
With C division, 2/d is 0 for d > 2. You are trying to take the logarithm of 0.