将数据从fortran转换到python

问题描述 投票:0回答:1

我是编程新手,现在想用Python脚本重写Fortran代码。

在原来的Fortran代码中,它声明实数为。

Begin
c----
      data (A(0,i), i=0,17)   
     &  /
     &    9.526e5, 1.416e6, 1.210e6, 7.734e5, 4.050e5, 1.851e5,
     &    7.944e4, 3.382e4, 1.434e4, 5.821e3, 2.174e3, 7.392e2,
     &    2.349e2, 7.361e1, 2.405e1, 8.423e0, 3.120e0, 1.176e0
     &  /
c----
c---- End

在这里,我怎样才能把A_ul(0,i)转换为Python代码?我如何重写A(0,i)来计算。

B = (p**2)*(c**3)*A_ul(0,i)

这样p和c是常数

python fortran77
1个回答
1
投票

两个选择

方案 1: 使用普通的 Python 列表

Python列表理解教程

A_ul = [9.526e5, 1.416e6, 1.210e6, 7.734e5, 4.050e5, 1.851e5,
        7.944e4, 3.382e4, 1.434e4, 5.821e3, 2.174e3, 7.392e2,
        2.349e2, 7.361e1, 2.405e1, 8.423e0, 3.120e0, 1.176e0]

# some values for p, c (assuming scalars)
p = 2.95
c = 3.41

# generate computation of scalar with array using list comprehension
B = [(p**2)*(c**3)*x for x in A_ul] 

print(B)

[328713655.56773156, 488619080.70954007, 417534666.42552507, 266877116.54008356, 139753338.76226252, 63872451.863937765, 27412358.595738605, 11670266.461579552, 4948303.402100851, 2008652.308481803, 750182.1196769351, 255075.72348904808, 81056.93648211227, 25400.60065750653, 8298.932832672626, 2906.524376282808, 1076.6183134278003, 405.80228736894003]

方案2:使用Python Numpy数组

Numpy允许在Python中进行简单的数组和矩阵表达式(即Matlab的替代品)

Numpy教程

import numpy as np

# A_ul as Numpy array
A_ul = np.array([9.526e5, 1.416e6, 1.210e6, 7.734e5, 4.050e5, 1.851e5,
        7.944e4, 3.382e4, 1.434e4, 5.821e3, 2.174e3, 7.392e2,
        2.349e2, 7.361e1, 2.405e1, 8.423e0, 3.120e0, 1.176e0])
# some values for p, c (assuming scalars)
p = 2.95
c = 3.41

# numpy understands multiplying scalars by arrays
B = (p**2)*(c**3)*A_ul 

print(B)

[3.28713656e+08 4.88619081e+08 4.17534666e+08 2.66877117e+08
 1.39753339e+08 6.38724519e+07 2.74123586e+07 1.16702665e+07
 4.94830340e+06 2.00865231e+06 7.50182120e+05 2.55075723e+05
 8.10569365e+04 2.54006007e+04 8.29893283e+03 2.90652438e+03
 1.07661831e+03 4.05802287e+02]
© www.soinside.com 2019 - 2024. All rights reserved.