You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cython 3中正确使用float128类型?

问题解决:Cython中np.float128_t类型错误

错误原因

np.float128_t并非Cython官方支持的numpy类型别名,且float128的支持高度依赖编译器、操作系统及numpy的编译配置——部分平台上numpy的float128实际映射为longdouble,直接使用float128_t会导致Cython类型解析失败。

正确实现方式

方案1:跨平台兼容的longdouble类型实现

修改sum_array.pyx,替换类型并添加Cython语言级别指令消除警告:

# sum_array.pyx
# 显式设置Cython语言级别,消除版本警告
# cython: language_level=3str

cimport numpy as np

def sum_array(np.ndarray[np.longdouble_t, ndim=1] arr):
    cdef int n = arr.shape[0]
    cdef np.longdouble_t total = 0
    cdef int i
    for i in range(n):
        total += arr[i]
    return total

方案2:针对支持float128的Linux平台

如果你的系统(如Linux+GCC)原生支持__float128类型,可直接使用C语言原生类型适配:

# sum_array.pyx
# cython: language_level=3str

cimport numpy as np
from libc.math cimport __float128

def sum_array(np.ndarray[np.float128_t, ndim=1] arr):
    cdef int n = arr.shape[0]
    cdef __float128 total = 0
    cdef int i
    for i in range(n):
        total += arr[i]
    # 转换为Python可识别的数值类型返回
    return float(total)

注意:此方案仅在GCC支持__float128的平台生效,Windows系统通常不兼容。

编译脚本保持不变

setup.py无需修改,继续使用原内容:

# setup.py
from setuptools import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize("sum_array.pyx"),
    include_dirs=[np.get_include()]
)

执行编译

运行原编译命令即可:

python setup.py build_ext --inplace

验证测试

编译完成后,用以下代码验证功能:

import numpy as np
import sum_array

test_arr = np.array([1.5, 2.7, 3.9], dtype=np.longdouble)
print(sum_array.sum_array(test_arr))  # 预期输出8.1

内容的提问来源于stack exchange,提问作者Simd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 07:18:15