samedi 7 juin 2014

Using fortranmagic in IPython notebook for sorting an array: no return value


Vote count:

0




I have to say that I am not a Fortran-programmer at all. I usually only use Python and C++, but sometimes colleagues have written great Fortran functions that would be great to implement in my Python code for efficiency. I was just about to try the f2py module via IPython's magic function.


For a trivial test, I have the following bubblesort implementation where I want to sort a Python list in place (which I convert to an numpy array laid out in memory the Fortran-style; I assume this would be more efficient than using Python lists right?)


However, the function has no return value here (None), and I am wondering where my mistake would be!?


The commands to install and load the fortranmagic which uses f2py



%install_ext http://ift.tt/1oIL7Nt
%load_ext fortranmagic


The Fortran bubblesort code:



%%fortran
SUBROUTINE fortran_bubblesort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
REAL :: temp
INTEGER :: i, j
LOGICAL :: swapped = .TRUE.

DO j = SIZE(a)-1, 1, -1
swapped = .FALSE.
DO i = 1, j
IF (a(i) > a(i+1)) THEN
temp = a(i)
a(i) = a(i+1)
a(i+1) = temp
swapped = .TRUE.
END IF
END DO
IF (.NOT. swapped) EXIT
END DO
END SUBROUTINE fortran_bubblesort


The execution:



x = np.asfortranarray([3,2,1])
y = fortran_bubblesort(x)
print(x, y)


The result:



[3 2 1] None


asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire