@cython.cdivision(True) 在奇怪的场景中导致“数学域错误”

问题描述 投票:0回答:1

在 VSCode 中运行 Jupyter 笔记本,我发现 Cython 不受保护的除法指令出现奇怪的行为。使用

%load_ext cython
开始会话,运行:

%%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

现在运行

simpleTest(x)
,对于任何
x
>= 3 的值,我得到:

ValueError:数学域错误

但是在没有

@cython.cdivision(True)
指令的情况下运行,它对所有
x
> 0 都可以正常工作,因为它应该。为什么该指令会破坏这种计算?有更好的方法吗?

math jupyter cython
1个回答
0
投票

您告诉 Cython 像 C 中那样进行除法。在 C 中,整数除法产生整数结果,向 0 舍入。

对于 C 除法,

2/d
0
代表
d > 2
。您正在尝试取 0 的对数。

© www.soinside.com 2019 - 2024. All rights reserved.