1

Now I am trying to rewrite the fortran code to python script.

In original fortran code, it declares real number as:

real a(n),b(n),D(64)

Here how can I convert this D(64) in python code? a(n), b(n) are values from the data which I used, but D(64) is not. I need to put this into sub-module fortran code which I wrapped with f2py. That sub-module code looks like below. M is just a integer which will be define in main code.

  subroutine multires (a,b,M, D)
  implicit none
  real a(*),b(*),D(*)
        .
        .

  if(nw.gt.1) D(ms+1)=(sumab/nw)
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Isaac
  • 885
  • 2
  • 15
  • 35

2 Answers2

4

If you code is looking for good performance, stay away from python lists. Instead you want to use numpy arrays.

import numpy as np
D = np.zeros((64), np.float32)

This will construct a numpy ndarray with 64 elements of 32 bit reals initialized to 0. Using these kind of arrays rather than lists can greatly improve the performance of your python code over lists. They also give you finer control over the typing for interoperability and you incur less overhead, especially if you get into cython.

Community
  • 1
  • 1
casey
  • 6,855
  • 1
  • 24
  • 37
2

Python is dynamically typed, so you have not to declare variables with their type. A Fortran array can be translated in a Python list, but as you should not want to dynamically add elements to the list, you should initialize it to its size. So Fortran real D(64) could become in Python:

D = [ 0. for i in range(64) ]

(declares D to be a list and initializes it with 64 0. values)

Of course, if you can use numpy and not just plain Python, you could use numpy.array type. Among other qualities (efficiency, type control, ...), it can be declared with F (for Fortran) order, meaning first-index varies the fastest, as Fortran programmers are used to.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thank you Serge Ballesta – Isaac Nov 03 '15 at 08:23
  • 2
    Shorter: `D = 64*[0.]` – Stefan Nov 03 '15 at 08:24
  • 5
    Fortran arrays are closest to Python arrays, not lists. (All items of the same type, storage space and time to access minimised). Python arrays are most commonly leveraged via the numpy module. If the Fortran code you are converting is at all computationally demanding, then you should be converting it using numpy, not vanilla Python. – nigel222 Nov 03 '15 at 10:03
  • @nigel222 your advice is very helpful. Thank you. – Isaac Nov 03 '15 at 19:28