Interfacing a dynamic shared library gives me different results in 2.7 versus 3.5

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon May 23 06:29:16 EDT 2016


On Monday 23 May 2016 13:15, Siyi Deng wrote:

> I have a dynamic library doing some numerical computations.
> 
> I used ctypes to interact it by passing numpy arrays back and forth.
> 
> Python 3.5 gives me the correct results.
> 
> Python 2.7 gives me different, erroneous results, but it never crashes.
> 
> How is this possible? There is no string operations involved whatsoever.

This is only a guess, because you haven't shown your code or data, but I guess 
it could be related to the change from integer division to true division in 
Python 3.

In Python 2.7, try this at the interactive interpreter. Do you get the same 
results?

>>> import numpy
>>> a =numpy.array([1, 2, 3])
>>> a/3
array([0, 0, 1])


That's because in Python 2, the / operator performs integer division, like C. 
In Python 3, it performs true division.

Put "from __future__ import division" at the top of your script. In Python 2.7, 
it will give you the same behaviour as Python 3, and in Python 3, it will be 
harmless. Note that there are TWO underscores at the front and end of 
__future__:


>>> from __future__ import division
>>> a/3
array([ 0.33333333,  0.66666667,  1.        ])



Please note that __future__ imports must be the FIRST line of code. They can 
follow comments, but must be before any other code.



-- 
Steve




More information about the Python-list mailing list