fortrans等效语法与C

Fortrans equivalent syntax to C++

本文关键字:语法 fortrans      更新时间:2023-10-16

我正在处理文件。内容的格式如下:

name   - problem name (A string value)
m      - number or rows (int value)
n      - number of columns (int value)
Ap     - pointers to the begining of storage of column (size n+1)(an array of size (n+1) )
Ai     - row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)
b      - right hand side (input, size m)(an double array of size m )
c      - objective vector (minimize, size n) (an double array of size n) )
z0     - initial fixed value for objective (double value)
lobnd  - lower bounds on variables (size n) (an double array of size n )
upbnd  - upper bounds on variables (size n) (an double array of size n )

在fortran中读取此文件的语法如下:

Ap (j) = location of start of column j
Ai (Ap (j)) through Ai (Ap (j+1)-1) are the row indices in column j
Ax (Ap (j)) through Ax (Ap (j+1)-1) are the numerical values in column j
      read(file,'(a8)') name
      read(file,*) m,n
      read(file,*) (ia(i),i=1,n+1)
      read(file,*) (ja(i),i=1,ia(n+1)-1)
      read(file,*) (a(i),i=1,ia(n+1)-1)
      read(file,*) (b(i),i=1,m)
      read(file,*) (c(i),i=1,n)
      read(file,*) z0
      read(file,*) (lobnd(i),i=1,n)
      read(file,*) (upbnd(i),i=1,n)

我想知道C 中的相应语法。有人知道如何将此程序从Fortran转换为C ?这是文件的示例。

根据上述文件格式的描述

name   = 'BLEND'
m      = 74  
n      = 114
upbnd  = I can see the n or 114 double values at the end of the file
lobnd  = I can see the n or 114 double values before the values of upbnd  
z0     = here I can see 0. is the value of z0
c      = I can see n or 114 values before z0 in the file and understand this
b      = I understand the right hand side and I can see the m or 74 values
Ai     - I understand row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)
Now I can not understand the following values in the file:
Ap     = I can not understand what do these (n+1) or 115 integers mean

我想了解文件中的此AP值。预先感谢。

read(file,'(a8)') name大致像scanf("%8s", name);

read(file,*) m,n大致等于file >> m >> n;

read(file,*) (ia(i),i=1,n+1)之类的线无疑是最棘手的。第一个逗号之后的部分是"隐含do循环"。这基本上意味着这大致相当于以下顺序:

for (int i=1; i<n+1; i++)
    file >> ia[i];

我相信其余的只是上面显示的一个或另一个的重复。

但是,还有一个要记住的一点:fortran存储阵列按列主要顺序。C和C 存储阵列以行订单为单位。这意味着,当您穿越C或C 的数组时,通常需要行遍历它。除其他外,这将优化缓存使用情况,因为每行都连续存储在内存中。

fortran是列。这意味着每列在内存中是连续的,并且遍历数组的自然方法是一次。由于每列在内存中都连续,因此(当然((当然(优化了缓存的用法。

AP中的值包含每列开头的位置。那就是AP(1(是第一列中第一项的索引。AP(2(是第二列中第一项的索引,依此类推。如果您需要读取N th 列,则AP(N(将告诉您主数组中的位置,您开始阅读以获取该列的数据。由于AP(n 1(是N 1列的开头,因此N列中的最后一项是AP(n 1(-1。

因此,假设您将主要数据数组读取到平面(1D(数组中,我们将仅致电data。要读取data中的N th 列,您可以使用Ap。例如,要打印出N th 列,我们可以写这样的代码:

void print_column(int n) {
    for (int i=Ap[n]; i<Ap[n+1]; i++)
        std::cout << data[i] << 't';
}

这使您可以避免进行动态分配2D数组的处理,而仅使用单个new/malloc/vector保存数据,以及第二个数据以保存每列开始的索引。在C 中,很容易创建一个2D矩阵类,该类使operator()超载以将2D地址用于vector中存储的数据。您可以使用Ap提供的额外间接级别,也可以使用乘法到达正确的位置。在当前处理器上,乘法可能比内存参考快,但是在较旧的处理器上,相对于内存访问,乘法通常要慢得多。