1. 安装Fortran编译器
在Debian系统上,GNU Fortran(gfortran) 是最常用的免费Fortran编译器,支持Fortran 90及以上标准。通过终端执行以下命令安装:
sudo apt update # 更新系统包列表
sudo apt install gfortran # 安装gfortran
安装完成后,通过 gfortran --version 验证安装是否成功,终端将显示编译器版本信息(如 GNU Fortran (Debian 12.2.0-14) 12.2.0)。
2. 配置开发环境(可选但推荐)
为提升开发效率,可安装以下工具优化工作流:
sudo dpkg -i package_name.deb 安装;打开VSCode,点击左侧扩展图标,搜索并安装 Modern Fortran(提供语法高亮、代码补全)和 Code Runner(一键运行Fortran代码)插件。cargo install fpm(需提前安装Rust)安装,后续可通过 fpm new my_project 创建项目、fpm build 构建、fpm run 运行。3. 编写基础Fortran科学计算程序
Fortran的核心优势在于高效的数值计算,以下通过两个常见示例展示其用法:
hello.f90 文件,内容如下:program hello
print *, "Hello, Scientific Computing with Fortran!"
end program hello
编译并运行:gfortran hello.f90 -o hello && ./hello,终端将输出提示信息。numerical_integration.f90 文件:program numerical_integration
implicit none
integer, parameter :: dp = selected_real_kind(15) ! 双精度浮点
real(dp) :: a = 0.0_dp, b = 1.0_dp, h, sum
integer :: i, n = 1000
h = (b - a) / n
sum = 0.5_dp * (func(a) + func(b))
do i = 1, n-1
sum = sum + func(a + i * h)
end do
sum = h * sum
print *, "Integral result: ", sum
contains
function func(x) result(y)
real(dp), intent(in) :: x
real(dp) :: y
y = x**2 ! 被积函数
end function func
end program numerical_integration
编译运行:gfortran numerical_integration.f90 -o integration && ./integration,终端将输出积分结果(约为0.333333)。4. 利用科学计算库提升功能
Fortran的科学计算依赖成熟的数值库,Debian系统可通过包管理器直接安装:
sudo apt install libblas-dev liblapack-dev。示例:调用LAPACK的 dgetrf 函数进行矩阵LU分解(需包含 lapack.f 头文件)。sudo apt install openmpi-bin libopenmpi-dev。示例:编写MPI程序实现矩阵加法(需使用 use mpi_f08 模块)。apt search 查找对应包安装(如 sudo apt install libfftw3-dev libhdf5-dev)。5. 编译与运行程序
gfortran source.f90 -o output 命令编译(如 gfortran hello.f90 -o hello);对于多文件项目,需先编译为对象文件(.o),再链接生成可执行文件(如 gfortran main.f90 utils.f90 -o my_program)。Makefile 文件(注意缩进为Tab),定义编译规则:FC = gfortran
FFLAGS = -O2 # 优化级别
SRCS = main.f90 utils.f90
OBJS = $(SRCS:.f90=.o)
TARGET = my_program
all: $(TARGET)
$(TARGET): $(OBJS)
$(FC) $(FFLAGS) -o $@ $^
%.o: %.f90
$(FC) $(FFLAGS) -c $<
clean:
rm -f $(OBJS) $(TARGET)
编译:make;清理:make clean。6. 并行计算支持(可选)
若需提升计算效率,可使用OpenMP实现多线程并行。安装OpenMP库:sudo apt install libopenmp-dev;编写并行程序(如计算π的近似值):
program parallel_pi
use omp_lib
implicit none
integer :: i, n = 1000000
real(8) :: sum = 0.0, pi
!$OMP PARALLEL DO PRIVATE(i) REDUCTION(+:sum)
do i = 1, n
sum = sum + 1.0 / (2.0 * i - 1.0)**2
end do
!$OMP END PARALLEL DO
pi = sqrt(8.0 * sum)
print *, "Estimated pi: ", pi
end program parallel_pi
编译时添加 -fopenmp 选项:gfortran -fopenmp parallel_pi.f90 -o parallel_pi;运行:./parallel_pi,终端将输出π的近似值。