ctypes' c_longdouble: underflow error (bug?)
Thomas Jollans
thomas at jollans.com
Wed Jul 14 12:28:42 EDT 2010
On 07/14/2010 03:24 PM, kj wrote:
>
>
>
> I have a C library function hg that returns a long double, so when
> I import it using C types I specify this return type like this:
>
> MYLIB.hg.restype = ctypes.c_longdouble
>
> But certain non-zero values returned by hg appear as zero Python-side.
> If I modify hg so that it prints out its value right before returning
> it, I get stuff like the following:
>
>>>> 0 == MYLIB.hg(100, 200, 100, 6000)
> from hg: 2.96517e-161
> False
>>>> 0 == MYLIB.hg(200, 200, 200, 6000)
> from hg: 5.28791e-380
> True
>
> So, although the value returned by hg in the second invocation
> above is 5.28791e-380, Python sees it as 0.
>
> What am I doing wrong?
Nothing.
http://docs.python.org/library/ctypes.html#fundamental-data-types
c_longdouble maps to float
http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex
"floating point numbers are implemented using double in C"
ergo, the extra precision a long double gives you versus a normal double
is lost if you use Python (or, at least, ctypes)
If you really want to keep the precision, you need a new/different type.
ctypes won't help you. Cython and NumPy may or may not be useful here.
- Thomas
More information about the Python-list
mailing list