Useful FortranNotes

合集下载

fortran教程

fortran教程

fortran教程Fortran是一种编程语言,用于科学和工程计算。

它具有高性能和可靠性,适用于大规模的数值计算和数据处理。

Fortran的基本语法是由一系列语句组成的程序。

每个语句都以一个数字标签开头,可用于控制程序的执行顺序。

以下是Fortran的一些基本语法和常用功能。

1. 变量和数据类型Fortran支持多种数据类型,包括整数(Integer)、实数(Real)和字符(Character)。

变量声明可以在程序的开头部分完成,例如:```fortranINTEGER :: iREAL :: xCHARACTER(len=10) :: name```注意,每个变量声明必须以两个冒号(::)开头。

2. 数学运算Fortran提供了一系列的数学运算符,用于执行基本的算术和逻辑运算,例如加法(+)、减法(-)、乘法(*)、除法(/)和求余(MOD)。

运算符的使用与其他编程语言相似。

3. 控制结构Fortran支持常用的控制结构,例如条件语句(IF-ELSE)和循环语句(DO LOOP)。

条件语句可以根据条件来执行不同的代码块,例如:```fortranIF (i > 0) THENPRINT*, 'i is positive'ELSEPRINT*, 'i is non-positive'END IF```循环语句可以根据条件重复执行一部分代码,例如:```fortranDO i = 1, 10PRINT*, iEND DO```上述代码将打印出1到10的数字。

4. 数组和矩阵运算Fortran支持多维数组和矩阵运算。

声明数组时可以指定维度和元素类型,例如:```fortranREAL, DIMENSION(3,3) :: matrix```然后,可以使用多个索引访问数组元素,例如:```fortranmatrix(1,2) = 3.14```这将给数组中的第1行第2列的元素赋值为3.14。

fortran 教学大纲

fortran 教学大纲

fortran 教学大纲Fortran 教学大纲Fortran(Formula Translation)是一种面向科学和工程计算的编程语言。

它在计算机科学的历史中扮演了重要角色,被广泛应用于科学计算、数值分析和大规模计算等领域。

本文将探讨 Fortran 教学的大纲,以帮助初学者系统地学习和掌握这门编程语言。

一、引言在本节中,我们将介绍 Fortran 的起源和发展,以及它在科学计算领域的重要性。

我们将讨论 Fortran 的特点,如其面向数值计算和高性能计算的优势,以及它对于科学家和工程师的实际应用。

二、基本语法和数据类型在这一部分,我们将介绍 Fortran 的基本语法规则和常用数据类型。

我们将讨论变量的声明和赋值,运算符的使用,以及控制流语句如条件语句和循环语句的编写方法。

此外,我们还将介绍 Fortran 中的基本数据类型,如整数、实数和字符类型,并讨论它们的使用场景和注意事项。

三、数组和矩阵运算Fortran 是一种强大的数组和矩阵运算语言。

在这一部分,我们将学习如何声明和操作一维和多维数组,以及如何进行矩阵运算。

我们将介绍 Fortran 中的数组索引和切片操作,以及常用的矩阵运算函数。

此外,我们还将讨论数组和矩阵的内存布局和性能优化技巧。

四、函数和子程序函数和子程序是 Fortran 中的重要概念,它们可以帮助我们组织和重用代码。

在这一部分,我们将学习如何声明和调用函数,以及如何编写和调用子程序。

我们将介绍函数的返回值和参数传递方式,以及子程序的参数传递和变量作用域。

此外,我们还将讨论递归函数和模块化编程的技巧。

五、文件操作和输入输出在科学计算中,数据的读取和保存是非常重要的。

在这一部分,我们将学习如何使用 Fortran 进行文件操作和输入输出。

我们将介绍如何打开和关闭文件,以及如何读取和写入数据。

此外,我们还将讨论格式化输入输出和二进制文件的处理方式,以及异常处理和错误处理的方法。

Fortran学习笔记.ppt

Fortran学习笔记.ppt

Free Format(自由格式)
Fortran 90 開始使用,附加檔名為 *.F90 不再規定第幾字元有何特定用途 驚嘆號「!」後都是註解 每行可以寫作 132 字元 如有行號放在每行最前面 程式連接符號改為「&」,放在每行程式碼最前或最後,表連結
前一行或是下一行
例如: 1:! free format 2: program free 3: read (*,10) a,b 4:10 format (f5.1,f5.1) 5: sum=a+b 6: write (*,20) & 7: sum 8:20 format (1x,f6.1) 9: end
2. 簡化的用法2:
不同格式控制指令,(1x,f5.2)可以移去逗號簡化成format (1xf5.2) 重複相同格式(a3,a3)不可以簡化成(a3a3),改用format (2a3) 若有不同格式時,如(1xf5.2 , 1xf5.2 , 1xf5.2)則改用format (3(1xf5.2))
書面格式
Fixed Format是舊式的寫法,有較多的限制, Fixed Format副檔名用 *.F 或 *.FOR 。
Free Format則是Fortran 90以後新增的作法,以副檔名 做為區隔,Free Format使用 *.F90。
Fixed Format(固定格式)
字元位置意義: 第 1 字元:如果是字母 C 或 c 或是星號 *,本行視為註解 第 1-5 字元:空白,或是一組數字為本行程式的代號 第 6 字元:放上 0 以外的字元,表示為接續上一行程式碼 第 7-72 字元:程式碼寫作區域 第 73 字元以後:不使用,編輯器會忽略,有些則發出錯誤訊息
3. 字串可以直接寫入格式內: write (*,"(a4,I1)") "1+2=",1+2 write (*,"('1+2=',I1)") 1+2 輸出均為 1+2=3 。上例中單雙引號混用,但F77只用使用單引號: write (*,'(''1+2='',I1)') 1+2

(最新整理)《FORTRAN95程序设计》学习笔记

(最新整理)《FORTRAN95程序设计》学习笔记

《FORTRAN95程序设计》学习笔记编辑整理:尊敬的读者朋友们:这里是精品文档编辑中心,本文档内容是由我和我的同事精心编辑整理后发布的,发布之前我们对文中内容进行仔细校对,但是难免会有疏漏的地方,但是任然希望(《FORTRAN95程序设计》学习笔记)的内容能够给您的工作和学习带来便利。

同时也真诚的希望收到您的建议和反馈,这将是我们进步的源泉,前进的动力。

本文可编辑可修改,如果觉得对您有帮助请收藏以便随时查阅,最后祝您生活愉快业绩进步,以下为《FORTRAN95程序设计》学习笔记的全部内容。

《FORTRAN 95程序设计》学习笔记66RPG gg★目录★《FORTRAN 95程序设计》学习笔记 (1)基础知识(基础、字符串、FORMAT、隐式、TYPE) (1)流程与控制(if、select、do) (4)数组(声明、隐式循环、整体操作、可变数组) (5)函数与子程序(子程序、函数、全局变量) (6)MODULE与面向对象(重载操作符、虚函数) (9)文件相关(OPEN、WRITE、READ) (10)指针(指向变量、数组、函数) (11)Visual Fortran 编译器(DLL,VB调用) (12)数值算法与IMSL(数值算法插件) (14)常用库函数(数学、数组、零碎、子程序) (15)基础知识(基础、字符串、FORMAT、隐式、TYPE)★【小玩意】二进制观察器:装在M.。

Visual Studio\DF98\bin,有一个Bitviewer,可以观察变量储存方式★【语法】续行:行结尾或行开头使用&符号;注释:使用 ! 符号★【语法】数学表达式:+ ;— ;*;/ ;( ;) ;**乘幂★【语法】程序结束:STOP (Ruby的exit)★【语法】输出:write(*,*),完整写法:write(unit=*,fmt=*)⏹建议:少用print,尽量用write★【语法】声明⏹整型:integer(kind=4) a ;其中kind是使用的bytes数,4 or 2◆其他写法:integer*4 a; integer(4) a⏹浮点:real(kind=4) a ;有效数位6位(12345678存为1。

Fortran语法(中级)

Fortran语法(中级)

Fortran语法(中级)!-----------------------------------------------------------------------EXTERNAL属性和哑过程 (哑元为外部过程,即哑过程)指定EXTERNAL语句或属性说明实元实际上是外部过程类型定义语句:类型,EXTERNAL :: 外部函数名[,外部函数名]…或EXTERNAL语句:EXTERNAL [外部函数名][,⼦程序名][,块数据名]…哑元也可以是⼀个过程,这时作为哑元的过程称为哑过程。

(⾄少两层调⽤)例如:!-----------------------------------------------------------------------Programm mainReal x,yExternal Plus !外部过程名作实元,必须⽤External说明,或者具有External属性x=1.0 ; y=2.0Print,* Calculate(x,y,Plus) !调⽤Calculate函数,实元为外部过程PlusEnd Program mainReal Function Plus(a,b) !(第⼆层被调⽤的外部函数)Real, Intent(In) :: a,bPlus=a+bEnd Function PlusReal Function Calculate (x,y,func)Real, Intent(In) :: x,yReal, External func !类型定义语句, 说明哑元时⼀个外部过程, 也可以直接⽤External说明Calculate=func(x,y) !调⽤⾃定义的外部函数End Function Calculate!-----------------------------------------------------------------------或者将 Real, External func 改为接⼝程序:InterfaceReal Function Plus(a,b) !Plus被接⼝块说明为⼀个哑元,即⼀个哑过程Real, Intent(In) :: a,bEnd Function PlusEnd InterfaceINTENT属性 (过程的哑元说明)在类型定义语句中:类型,INTENT(意图说明符) :: 哑元名表或⽤INTENT语句: INTENT(意图说明符) :: 哑元名表意图说明符为以下字符串:IN 指明哑元仅⽤于向过程提供数据,过程的执⾏期间哑元不能被重定义或成为未定义的,相联合的实元可以是常数、变量、数组以及它们的算术表达式。

fortran 编程指南

fortran 编程指南

fortran 编程指南英文回答:Fortran is a programming language that was developed in the 1950s and is still widely used today, especially in scientific and engineering applications. It stands for Formula Translation and was designed to be used for numerical and scientific computing. Fortran has evolved over the years and the latest version is Fortran 2018.One of the main advantages of Fortran is its efficiency in handling numerical computations. It has built-in support for arrays and mathematical functions, making it ideal for scientific calculations. Fortran also has a strong static typing system, which helps catch errors at compile-time and improves performance.Another benefit of Fortran is its extensive library of mathematical and scientific functions. These libraries provide a wide range of pre-written code for tasks such aslinear algebra, numerical integration, and solving differential equations. This saves programmers time and effort, as they don't have to write these functions from scratch.Fortran also has a long history and a large communityof users, which means there are plenty of resourcesavailable for learning and troubleshooting. There are numerous books, tutorials, and online forums dedicated to Fortran programming. This makes it easier for beginners to get started and for experienced programmers to find help when needed.One of the drawbacks of Fortran is its syntax, whichcan be seen as outdated compared to modern programming languages. It uses a fixed-format style, where each linehas a specific structure and indentation is not significant. This can make the code look less readable and harder to maintain.Furthermore, Fortran is not as versatile as some other languages when it comes to non-numerical tasks. It lacksbuilt-in support for string manipulation and file I/O operations, which can be limiting in certain applications. However, there are ways to work around these limitations by using external libraries or interfacing with other languages.In conclusion, Fortran is a powerful language for numerical and scientific computing, with a long history and a large community of users. It offers efficiency, extensive libraries, and plenty of resources for learning and troubleshooting. While its syntax may be seen as outdated, it remains a popular choice for scientific and engineering applications.中文回答:Fortran是一种编程语言,于1950年代开发,并且至今仍广泛应用于科学和工程领域。

fortran语言程序设计知识点

fortran语言程序设计知识点

fortran语言程序设计知识点Fortran语言是一种面向科学与工程计算的编程语言,因其在数值计算和科学应用方面的高效性而受到广泛使用。

本文将重点介绍Fortran语言程序设计的一些重要知识点。

一、基础语法1.1 变量与数据类型在Fortran中,变量是用于存储数据的容器。

常见的数据类型包括整型(INTEGER)、实型(REAL/DOUBLE PRECISION)、复数型(COMPLEX)、逻辑型(LOGICAL)等。

变量的命名需遵循一定规则,如以字母开头,长度不超过31个字符等。

1.2 运算符与表达式Fortran支持常见的算术运算符(如+、-、*、/)以及逻辑运算符(如. AND.、. OR.、. NOT.)等。

表达式由变量、常数和运算符组成,可以进行数值运算和逻辑判断。

1.3 控制结构Fortran提供循环结构(DO)、条件结构(IF-THEN-ELSE)和选择结构(SELECT CASE)等控制语句,用于控制程序的流程。

二、数组与数据处理2.1 数组定义与操作Fortran中数组是由相同类型的数据元素组成的集合。

可以使用DIMENSION语句定义数组的维度和大小,通过下标访问和修改数组元素。

2.2 数组运算与函数Fortran提供了许多对数组进行运算和处理的函数,如数组求和(SUM)、最大最小值(MAX、MIN)、数组重排(RESHAPE)等,方便对数据进行统计和处理。

2.3 文件读写操作Fortran支持对文件进行读写操作,可以通过OPEN语句打开文件,使用READ和WRITE语句读取和写入数据。

可以根据需要设置文件的访问模式和格式。

三、过程与模块3.1 过程(Subroutine/Function)过程是一段独立的代码块,可接受传入参数并返回值。

在Fortran中,过程可以是子程序(Subroutine)或函数(Function)。

子程序用于完成一系列操作,而函数则返回一个值。

3.2 模块(Module)Fortran中的模块是一个编译单元,用于组织和管理相关的过程和变量。

fortran语法手册范本

fortran语法手册范本

1 FORTRAN77四如此运算符+ - * / ** (其中**表示乘方)在表达式中按优先级次序由低到高为: +或-→*或/→**→函数→()2 FORTRAN77变量类型2.1 隐含约定:I-N规如此但凡以字母I,J,K,L,M,N六个字母开头的,即认为是整型变量,其它为实型变量。

如 IMPLICIT REAL (I,J)三种定义的优先级别由低到高顺序为:I-N规如此→IMPLICIT语句→类型说明语句,因此,在程序中IMPLICIT语句应放在类型说明语句之前。

2.4 数组的说明与使用使用I-N规如此时用DIMENSION说明数组,也可在定义变量类型同时说明数组,说明格式为:数组名(下标下界,下标上界〕,也可省略下标下界,此时默认为1,例:DIMENSION IA(0:9),ND(80:99),W(3,2),NUM(-1:0),A(0:2,0:1,0:3)REAL IA(10),ND(80:99)使用隐含DO循环进展数组输入输出操作:例如WRITE(*,10) ('I=',I,'A=',A(I),I=1,10,2)10FORMAT(1X,5(A2,I2,1X,A2,I4))2.5 使用DATA语句给数组赋初值变量表中可出现变量名,数组名,数组元素名,隐含DO循环,但不许出现任何形式的表达式:例如DATA A,B,C/3*-1.0/CHARACTER*6 CHN(10)DATA CHN/10*' '/INTEGER NUM(1000)DATA (NUM(I),I=1,500)/500*0/,(NUM(I),I=501,1000)/500*1/3 FORTRAN77程序书写规如此程序中的变量名,不分大小写;变量名称是以字母开头再加上1到5位字母或数字构成,即变更名字串中只有前6位有效;一行只能写一个语句;程序的第一个语句固定为PROGRAM 程序名称字符串某行的第1个字符至第5个字符位为标号区,只能书写语句标号或空着或注释内容;某行的第1个字符为C或*号时,如此表示该行为注释行,其后面的内容为注释内容;某行的第6个字符位为非空格和非0字符时,如此该行为上一行的续行,一个语句最多可有19个续行;某行的第7至72字符位为语句区,语句区内可以任加空格以求美观;某行的第73至80字符位为注释区,80字符位以后不能有内容。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Logical operands:.and. , .or. , .eqv. , .neqv. , .not.----------------------------------------------------------------------------------String concatenate:“The quick brown fox”//” ”//”jumps over the lazy dog”----------------------------------------------------------------------------------Use type_name(expr-list) to initialize a derived data type, for example : type stringcharacter(20)::valueinteger::lengthend type stringand later:type(string)::s = string(“This is a string”,16)-------------------------------------------------------------------------------- Assignment of a pointer:X => z, X is a pointer, z is a variable---------------------------------------------------------------------------------Also we can useX => null() to let X pointing to a null address------------------------------------------------------------------------------------------------------------------------------------------------------------------Select construct[name:] select case (expr)case selector [name]BlockDo(loop) construct:Do i = 1,n…end doUse “continue”(or ”cycle”)and “exit” in Fortran “do” loops as we use “continue” and “break” in C “while” loops“continue” can also be used as a “do thing” place holder---------------------------------------------------------------------------------Taking function as an argument:Function “minimum” takes another function “func” as an argument and minimize it.In this following example also notice how “internal” functions are declared and used. Note that theA function/subroutine with optional arguments can be called like:Call some_subroutine(n,f,x, option1=.yes., option3=.no.,)While you can guess that “option2” is omitted.In the function/subroutine itself, use intrinsic procedure present(option2) is test if a particular argument is being provided. If not, present(option2) will return .false.When defining a funct ion/subroutine, use “OPTIONAL” attribute if this argument is optional.---------------------------------------------------------------------------------------------------An example of a recursive function. If a function calls itself, the function name has ambiguous meanings between “a call to itself” and “its return value”. In this case, add a “result()” clause after function name to give another name to its return value. If a function is indirectly recursive, i e. it calls some functionWhen a string is used as argument and its length is unknown, we may use character(len=*)::string or simply character(*)::string as the declaration. We can use len(string) in runtime to actually test its length ----------------------------------------------------------------------------------------------------R andom number generator in fortran is subroutine “random_number(r)”. Use “call random_number(r)” to get a random value between 0.0 and 1.0 written in r.----------------------------------------------------------------------------------------------------(Not confirmed) Whenever a pointer appears on LHS of a statement, the RHS could be pointers, variables, arrays, pointer to arrays, etc. However always use ‘=>’ to indicate a change of pointer itself no matter whether the RHS is a variable or a pointer. If we use a ‘=’when the LHS is a pointer, it’s always a change of the object associated by the pointer.-----------------------------------------------------------------------------------------------------Looks like an allocated array will automatically deallocate if it’s out of domain, except that a “save”attribute is applied. But “save” attribute is more like “static” in C.It’s saved so it can be visited when the function is called next time. Can we use a function to allocate some memory for outer space? Looks like it’s ok. However when no variable is associated with that piece of memory, it’ll be released (Looks likeUse “associated(p)” to test if p is a null pointer. Use nullify(p) or p=>null() to make p dissociated. But nullify(p) won’t deallocate the memory p points at. Except p is the only variable pointing to that memory at this time.-----------------------------------------------------------------------------------------------allocate() and deallocate() can take an extra argument as allocate(array(x,y),stat = flag) ordeallocate(array, stat=flag). flag should be an integer. flag value after calling the procedure indicateswhether the call is successful (flag==0) or not (flag!=0). Try to deallocate an array/pointer which is already deallocated will yield non-zero stat value.Also, after allocation, we can use allocated(array) to test if the array is successfully allocated, given that we didn’t test it when calling allocate().-----------------------------------------------------------------------------------------------Operations that can apply to each element of an array is called “elemental”. Intrinsic procedures such as +, -, *, /, sin(), cos(), etc are all elementary. User defined procedures are NOT automatically elementary. We can define the polymorphism to let it be elemental, like the example below, operator(+) is now elemental as long as only 1-dimensional arrays are involved. Notice “size(a)” can dynamically determine the array length of an input array.An alternative way is to declare it as “elemental”. See the 4th nextWhere statement:where (array_name > 0)array_name = some_new_valueend where-----------------------------------------------------------------------------------------------Forall statement:forall statement is a little bit like “for” statement in C:forall(i=1:n, j=1:n)do something related to i,jend forallForall statement can also be “forall(i=1:n, j=1:n, array(i,j)/=0)”, or nested likeforall(i=1:n)forall(j=1:n)some actionend forallend forallTechnically, DO while asks the program to do the loop following the exact order, while forall statement allows the loop to be completed in any order. Thus forall tells the cpu to “go parallel if it’s possible”-----------------------------------------------------------------------------------------------We can “name” do loops, if statements, select clauses, etc, in case if a loop is large, we can keep track on which level we are in if we meet an “end” statement. It’ll also help compilers and debuggers to generate diagnostic information if something goes wrong.----------------------------------------------------------------------------------------------“pure” attribute added in front of a function means this function has no “side effect”, i e. it won’t change values of it arguments or any global variable. It’s like “const function” in C. Note that there is no “pure” subroutin e, since subroutines are meant to have “side effects”-----------------------------------------------------------------------------------------------“elemental” attribute allows a function to be elemental. Elemental functions must be “pure”, and its return value must be a scalar instead of an array (not even the array is fixed length). If an elemental function calls another function, the other function must also be elemental.-------------------------------------------------------------------------------------------------Can we declare “array of pointers”? Not directly since integer,dimension(:),pointer::p defines a pointer which points to a array (1 pointer) but not an array of pointers (multiple pointer). We can work around this by wrap a pointer into a type structure, and define arrays of that type.-------------------------------------------------------------------------------------------------Array constructor. Use array = (/1,2,3,4/) to construct an array. Use array = reshape((/1,2,3,4/),shape = (/2,2/)) to construct a multi-dimensional array.-------------------------------------------------------------------------------------------------The attributes of “private” and “public” can be used in modules and derived typesreal, public::ainteger,private,dimension(:)::arrayor if we defined some functions in this module, and later specify that:private::function_name1, function_name2-------------------------------------------------------------------------------------------------If some function arguments are optional, use the “optional” attribute for dummy arguments. As said before, use the intrinsic method “present()” to determine whether an argument is given and whether it needs a default value.-------------------------------------------------------------------------------------------------The “save” attribute equals “static” in C. It can appear in functions/subroutines and modules and maintain its value during the whole lifetime of a program-------------------------------------------------------------------------------------------------Use “date_and_time()” intrinsic function to get date and time.Use associated(p1,variable) or associated(p1,p2) to find whether p1 points to variable or p1,p2 point to the same address.-------------------------------------------------------------------------------------------------READ(*,*) var1,var2 takes two *. The first * means the input device is standard input. The second * means “list-directed input”,or “read whatever you need” reading mode.-------------------------------------------------------------------------------------------------Strings (“character(len=xx)::string”)can be compared using standard relational signs such as <, >, ==, >=, The difference between <,>,>=,<= and LGT, LLT, LGE, LLE: <,>,>=,<= depends on the characters set the computer is using, if the computer uses a character set other than ASCII, the result may be different. On the other hand, LGT, LLT, LGE, LLE are guaranteed to produce result based on ASCII order. So always use LGT, LLT, LGE, LLE since they are portable. However there is no equivalent function as ==, since string equivalency doesn’t depend on character set, just use == and /= if we want to check whether two strings are equal or not.Some methods for strings: len(), len_trim(), trim(). Some methods just for characters: achar(integer), ASCII index to char, iachar(character), character to ASCII index. “a” here means ASCII. char(integer) and ichar(character) are also available, given that char() and ichar() are based on the computer’s local character set. So always use iachar() and achar()!INDEX(str1,str2,back): returns the location of str2 appears in str1. Returns 0 if str2 is not substring ofstr1. “back” is an optional logical argument which, if present, makes the search backward.-------------------------------------------------------------------------------------------------Formatted output:I refers to integer, F refers to real, L refers to logical, E refers to scientific, A refers to character/string as we already know. ES also refers to scientific but will show a number like 1.3E4 (E will show it like 0.13E5). nX means adds n blank spaces. T is very useful, T51 means jumping to column 51 immediately. We can also jump “backward” to make output overlaps.Output expression can be grouped, such like write(*,'(3(I3,3X))'),i,i+1,i+2Slash ‘/’ equals \n in C, just starts a new line.It’s advised in Fortran to allow one blank space at the beginning of each line, to avoid some archaic mechanism of line change by placing a ‘1’ at the beginning of each line.-------------------------------------------------------------------------------------------------In “READ”, formats are similar to WRITE, but there are slight differences.When reading a string, if we specify character(len=10) str; READ(*,’(A)’) str, then it’ll read 10 characters and write into str. But if we READ(*,’(A5)’) str, it’ll only read 5 characters and write to the left half of str. If we READ(*,’(A15)’), then it’ll read 15 characters from the input, but only the right 10 characters from what was read can be written into str.‘/’ can be used to ignore the rest of the line; X can be used to skip a certain length of fields.‘T’ can be used to jump to a specific location, or jump back to read the data again.If a READ() did no read enough data, it will simply stop, and the current line it was reading will be discarded. The next READ() will start a new line to continue reading.-------------------------------------------------------------------------------------------------File descriptor is a integer number, it can be obtained from OPEN() method. There are some default file descriptors that are not guaranteed to work on every machine, including 5 for stdin, 6 for stdout, 0 for stderr. Avoid using them but be sure once encountered, we know what it means. However, asterisk * is guaranteed to be stdin/stdout on any machine.READ(UNIT=int_expr, FILE=char_expr, STATUS=char_expr, ACTION=char_expr, IOSTAT=int_expr) UNIT: file descriptorused. It must be nonnegative. Note it’s an INPUT parameter not an OUTPUT parameter. We need to specify a number for it instead of waiting the system to return a number for us! FILE: file name to openSTATUS: ‘OLD’, ‘NEW’, ‘REPLACE’,’SCRATCH’,’UNKNOWN’, optional, default ‘UNKOWN’ACTION:’READ’,’WRITE’,’READWRITE’IOSTAT: returns 0 means successful, otherwise unsuccessful and it’s an error code.If we want to read from an opend file, each time we read, we should used IOSTAT flag: READ(file_descriptor, fmt, IOSTAT = status)and check the IOSTAT flag status. If it’s non-zero, then we already reached the end of file. We should terminate reading and exit the loop.We can use BACKSPACE(file_descriptor) to go back one record(I think which means one line), or use REWIND(file_descriptor) to return beginning of file.-------------------------------------------------------------------------------------------------Note that READ in fortran and also read from a string, like sprintf in C or istringstream in C++. Similarly write statement can also write to string, just use:READ(string, ‘(I3, F4.8, …)’), i, a,or WRITE(string, fmt), variables..-------------------------------------------------------------------------------------------------character(len=*)::str is usually used in functions/subroutines as dummy variables. It simply means “I don’t know it’s length”. It’s memory space will be allocated once actual arguments are passed.-------------------------------------------------------------------------------------------------What’s the difference between a function/subroutine defined not in a module/program or is defined within a module/program? Function/subroutine defined outside of module/programs are said to havehowever the result is wrong since a real number is mistreated as an integer.Conclusion: always define subroutine/functions within modules, or use explicit interfaceP.S. when used assumed-shape or assumed-length arrays as dummy variables, explicit interfaces are mandatory. Also for functions they need to be declared in callers like regular variables if not defined in modules.-------------------------------------------------------------------------------------------------Some useful array functions:ALL(mask), true if all values are true; ANY(mask), true if any one value is true;COUNT(mask), count number of trues;DOT_PRODUCT(A,B), dot_product of two vectorMATMUL(A,B) matrix product of two conformable matrixesMAXLOC(array, mask), MAXVAL(array, mask), MINLOC(array,mask), MINVAL(array,mask); find location/value of maximum/minimum element in array, mask is optional but if given, elements that are masked out are ignored.PRODUCT(array,mask), SUM(array,mask); product/sum of elements in array given mask is true. mask is optional.RESHAPE(array,shape), TRANSPOSE(array); they are self-evident;In the above functions, “mask” means an array with all logical elements.-------------------------------------------------------------------------------------------------If we want to return a string from a function, use form A instead of form B: B is OK but is an obsoleteThere is no such thing like atoi() or atof() in Fortran. Instead, we can use READ to convert a string into floating number or integer: “READ(string, ‘(F)’), a”, Assuming string is type CHARCTER(*) and a is type REAL-------------------------------------------------------------------------------------------------We can define types of real numbers using REAL(KIND=kind_number)::a to specify a kind for the real number. However the kind_number is dependent on CPU type. For example for x86 systems,kind_number usually means number of bytes it takes, such as kind=4 means a “single” precision floating number like “float” in C, and kind=8 means a “double”. The only portable way to specify a kind_number is to use:kind_number = SELECTED_REAL_KIND(p=precision,r=range)(either p or r is optional, but not both) to specify the precision and range we need. For example: kind_number = SELECTED_REAL_KIND(p=6, r=37)means a precision of 6 digits and range of +-10^37. Other useful methods include:KIND(x): the kind of some number xPRECISION(x):, RANGE(x)For a “double”, it’s precision and range is 15 and 307. So SELECTED_REAL_KIND(15,307) will be guaranteed to yield a 8 byte “double” on every computer.“float” actually is (6,37)Note: The largest possible integer kind on my computer is actually int64 with range 10^18An intrinsic function called DBLE() can convert a number into double precision number, but as just said what “double precision” means is CPU dependent.-------------------------------------------------------------------------------------------------Functions related to COMPLEX type:CMPLX(a,b,kind): conversion from two reals to a complexREAL(c), INT(c): convert the real part of a complex into a real or an integerAIMAG(c): convert the imaginary part of a complex into a realCABS(c): absolute valueCONJG(c): its conjugate-------------------------------------------------------------------------------------------------SEQUENCE attribute asks the compile to arrange elements within a type structure accorder to their order in the source code. It’s useful when a type structure is passed to a module written in another language (interoperability with C perhaps).-------------------------------------------------------------------------------------------------extension name.Type can also take parameters, like:(NOT YET IMPLEMENTED IN MOST COMPILERS)type vector(kind,n)INTEGER,KIND::kind = KIND(0.) if kind is not given , use KIND(0.) as defaultINTEGER,n = 3 if n is not given, use 3 as defaultREAL(kind),DIMENSION(n)::vend type vectorThe type parameters here are like template parameters in C++, except that they can’t specify data types (, which can implement metaprogramming). Unfortunately this feature has not supported yet in 2014 by compilers such as gfortran.Types which are not SEQUENCE or BIND(C) can be extended (inherited), like this:type, EXTENDS(vector):: vector_with_colorINTEGER::colorend type vector_with_colorGiven a vector_with_color object named vc, we can refer its elements like vc%v or vc%parent%v, both are OK. (After testing, vc%parent%v don’t work on my compiler, so just use vc%v).Types can have associated functions(member function). Member functions must be declared as procedure,pass::function_name() but defined outside the type but inside the module. “pass” means the first argument of the function will be the object itself.If we want to use functions/subroutines defined within a module, we can simply use that module. But there are cases where function/subroutines are not defined within a module, for example legacy codes, or library written in C. In this case, we need to define interfaces within caller module. The interface simply repeats the header of called functions/subroutines. If we have a legacy library consists of a large set of functions/subroutines written without any module, we can create an interface for each function/subroutine and put all interfaces in a single module. Using the “interface module” allow us to call those functions/subroutines without further difficulty.-------------------------------------------------------------------------------------------------Interface GenericFunctionNameSubroutine AppliedToFirstTypeOfInput(a)…End SubroutineSubroutine AppliedToSecondTypeOfInput(a)…End Subroutine…End Interface GenericFunctionNameThen later you need to define AppliedToFirstTypeOfInput and AppliedToSecondTypeOfInput separately (within the same module which contains the interface section). Then later you can call the generic function name GenericFunctionName() to deal with different types of functions.Methods bound to derived types(member functions) can also be generic. You need to : TYPE::pointREAL::x,yCONTAINSGENERIC::add=>point_plus_point, point_plus_scalarThen define point_plus_point and point_plus_scalar like normal member function.Operators can also be overwritten like:INTERFACE OPERATOR(operator_symbol)MODULE_PROCEDURE function_1MODULE_PROCEDURE function_2…END INTERFACEThen define function_1 and function_2 normally.for (=), it must be INTERFACE ASSIGNMENT(=) and the overloaded method must be a subroutine. Corresponding operators overloading in member functions are:TYPE ……CONTAINSGENERIC::ASSIGNMENT(=) => assign_subroutineGENERIC::OPERATOR(+) => plus1, plus2, plus3,……END TYPE …-------------------------------------------------------------------------------------------------When declared Public, attributes/methods can be calledWhen Private, can’t access from outside module. When Protected, it’s read-only outside of module. There are several ways to declare the data hiding level:Way 1: add public, private, protect to each attribute:INTEGER,PUBLIC::iREAL PRIVATE FUNCTION f()Way 2: use a list to declare who is private, who is publicPUBLIC:: i, fPRIVATE::a,jWay 3: use an empty list PRIVATE to make all of them private, then a public to say what are exceptions: PRIVATEPUBLIC::a,i<- (Preferred)-------------------------------------------------------------------------------------------------USE module_name, ONLY:fun1, fun2_renamed=>fun2allows partial use of a module and renaming-------------------------------------------------------------------------------------------------subroutine GET_COMMAND(command,length,status): writes the whole command(including program name into command. If command has not enough space to write the whole string, state /=0) status==0 if successfulsubroutine GET_COMMAND_ARGUMENT(number,value,length,status): writes i-th argument into value. status ==0 if successful. 0-zero argument is the program name itself.-------------------------------------------------------------------------------------------------It tries to find an environmental variable with the name same as “NAME” and writes its value into “VALUE”. status == 0 if found, and writing into VALUE is successful. If TRIM_NAME is .true., it tries to find an environmental variable named as trim(NAME).-------------------------------------------------------------------------------------------------If we want a pointer to associate with a (static) local variable, the variable must be declared as TARGET. However if a pointer is associated with an allocated data, there is no such restriction because the allocated data don’t have to be declared, like this:INTEGER, pointer::piAllocate(pi); pi = 3;A pointer can be in three states, undefined as it’s first declared; associated as it’s a nor mal pointer and pointing to something; dissociated means after pi=>null() or nullify(pi); If we use associated(pi) to test it, it will give True only in the second case.The only reason to choose null() instead of nullify is at the moment of declaration, only => null() is usuable:INTEGER, pointer::pi => null(); but nullify() can’t be used here.Whenever a pointer appears in an expression, except in the LHS of a ‘=>’, always treat it just like the variable it points to.Caution: Use allocatable arrays won’t cause memory leak, but using pointers to allocate space withoutattributes apply to this module. 2. Easy to use, just use the module.∙Use “type Unit” to define a class∙Use “type, extends(Unit):: AdvancedUnit” to inherit a class∙Use “class(AdvancedUnit),pointer::p” to declare a pointer that can be associated wit h any object of Unit family so it can exhibit polymorphism.∙This is no such thing as “constructor”, when declare an object, use Unit::u = Unit(v1, v2) to initialize its first and second members with v1 and v2. If its members are private, then we can’t use this kind of method to construct an object. There is no “Constructor” when enables us to construct an object from a function.∙Private members can’t be accessed from inheriting classes∙Use “FINAL” keyword to mean it’s a finalizer like this: finalizer must b e a subroutine with no∙∙∙DEFERRED attribute denotes it’s a virtual function. A class with a virtual function is a virtual class which can’t have objects.。

相关文档
最新文档