An Extended Set of Fortran Basic Linear Algebra Subprograms
- 格式:pdf
- 大小:66.89 KB
- 文档页数:23
FAQ之常见错误2014-02-02 13:45:35 来源:Fcode研讨团队评论:2点击:4419本文从编译错误,链接错误,运行时错误,计算结果错误等四个方面介绍了常见的错误及解决思路。
适合初学者阅读。
首先应该明确:错误有哪几种?我们当前遇到的是何种错误?阐述这些问题前,我们先讨论一下常规的应用程序开发的过程:1>>编写代码,使用一个或多个源代码文件。
2>>对第一步的每一个源代码文件执行编译操作。
得到一个或若干个目标代码。
3>>将目标代码,运行时库(Run-time Library)和其他使用到的函数库链接起来。
得到一个可执行文件(EXE 或其他)4>>编写程序的说明书,必要的(输入)数据文件5>>将上述得到的结果发布给用户。
(发布的方式可以是刻录成光盘,销售,放在网站上供别人下载,或者其他)6>>用户得到程序后,运行,输入数据,得到计算结果。
对于很多 Fortran 程序员来说,可能用户就是自己,也可能仅仅是自己教研室的同事同学。
所以第4,5,6步骤很多时候不明显。
而如果使用集成开发环境(IDE)进行开发,第1,2,3步骤又可以一键完成。
因此,很多初学者就认为,写程序就是:输入代码,运行,得到结果。
这样的理解太狭义。
不管我们面对什么使用者来写代码,程序开发应该是上述的过程。
我们的编译器,编译环境,也是为这个过程而设计的。
于是,我们将错误分为四种:一. 编译错误(发生在第2步)编译错误,一般是源代码书写格式不正确,不符合语法要求。
二. 链接错误(发生在第3步)链接错误,一般是源代码结构不完整,运行时库或函数库使用不合理。
三. 运行时错误(发生在第6步)运行时错误,一般是执行代码时,遇到了事先未料及的错误。
比如内存不足了,磁盘空间不够了,输入文件格式不对了,输出文件写入失败了等等。
四. 计算结果不符合预期(程序代码不规范,或不符合你的设想)计算结果不符合预期,可能性就很多了。
fortran断点指令## Fortran Breakpoint Statement.A breakpoint statement is a special statement that can be placed in a Fortran program to cause the program to stop executing at that point. This can be useful for debugging purposes, as it allows the programmer to examine the stateof the program at a specific point in time.The breakpoint statement is written as follows:BREAK.When the program reaches a breakpoint statement, itwill stop executing and display a message to the user. The user can then use the debugger to examine the state of the program and make any necessary changes.Here is an example of how to use a breakpoint statement:program breakpoint_example.implicit none.integer :: i.do i = 1, 10。
print , 'i = ', i.if (i == 5) then.BREAK.end if.end do.end program breakpoint_example.When this program is run, it will print the following output:i = 1。
. Fortran 运行中给出的系统错误及解决方法以下均为linker tools errors and warningsLinker Tools Error LNK1000unknown error; consult documentation for technical support options Note the circumstances of the error, try to isolate the problem and create a reproducible test case, then contact technical support.Linker Tools Error LNK1101incorrect MSPDBxx.DLL version; recheck installation of this product The version of MSPDBxx.DLL available on your system does not match the version required by this tool.Linker Tools Error LNK1102out of memoryThere was not enough memory for the tool to run. Probably the paging file exceeded available disk space. If a shortage of disk space is not the cause, note the circumstances of the error, try to isolate the problem and create a reproducible test case, then request technical support.Linker Tools Error LNK1103debugging information corrupt; recompile moduleProbably the compilation was terminated before a valid object file was created.Recompile the given object file. If recompiling does not correct the problem,note the circumstances of the error, try to isolate the problem and create a reproducible test case, then consult technical support.Linker Tools Error LNK1104cannot open file "filename"The tool could not open the given file. One of the following may be a cause:l There was not enough disk space.l The file does not exist.l The filename or its path was incorrectly specified.l The specified drive is invalid.l The file does not have the appropriate permissions.l The path for filename expands to more than 260 characters.l If the given file is named LNKn, which is a filename generated by the linker for a temporary file, then the directory specified in the TMP environment variable may not exist, or more than one directory is specified for the TMP environment variable. (Only one directory path should be specified for the TMP environment variable.)l If the error occurs on the executable filename, an earlier version of the executable may still be running. You will need to terminate the executable before linking it. In Windows NT (including Windows 2000) or Windows 95,you can use the utility PVIEW to look for and kill instances of the application.l If the error message occurs for a library name, and you recently ported the .MAK file from a previous Microsoft Visual C++ developmentLinker Tools Messages Page 3 of 37environment, the library may no longer be valid. Ensure that the library still exists in this circumstance.l If the error message occurs for a library name such as CONSOLE.LIB, and you included object modules from an older Fortran developmentenvironment such as Microsoft Fortran PowerStation, recompile all source files with Visual Fortran to create new object files and libraries.Linker Tools Error LNK1105cannot close file "filename"The tool could not close the given file. Possibly there was insufficient disk space available.Linker Tools Error LNK1106invalid file or disk full: cannot seek to locationThe tool could not read or write to location in a memory-mapped file:l Your disk may be too full to complete the link. Free up some space and try the link again.l The error may be a result of trying to link over a network. Some networks do not fully support the memory-mapped files used by the linker. Try linking on your local disk to see if that fixes the problem.l There may be a bad block on your disk. Although the operating system and disk hardware should have detected such an error, you may want to run a disk checking program.Linker Tools Error LNK1107invalid or corrupt file: cannot read at locationThe tool could not read the file. Recreate the file.Linker Tools Error LNK1108cannot write file at locationThe tool could not write to the file. One of the following may be a cause:l There was not enough disk space to create the file.l The drive being written to was not available, possibly due to a network problem.Linker Tools Error LNK1109cannot remove file "filename"LIB could not delete the given file. Before LIB writes the new version of a library, it removes the existing library file. One of the following may be a cause:l The given file does not have the appropriate permissions.l The drive containing the file was not available, possibly due to a network problem.Linker Tools Error LNK1110Linker Tools Messages Page 4 of 37cannot rename file "filename"LIB could not rename the given file. When LIB builds a new version of a library, it creates atemporary file, then renames the file. One of the following may be a cause:l The given file does not have the appropriate permissions.l The drive containing the file was not available, possibly due to a network problem.Linker Tools Error LNK1111invalid /BASE argument "argument"The /BASE option was incorrectly specified. Either no argument was specified or argument is not a number.Linker Tools Error LNK1112module machine type "type1" conflicts with target machine type "type2"The object files specified as input were compiled for different machine types.Linker Tools Error LNK1113invalid machine typeThe machine type specified in the object header is not valid. Probably the file is corrupt. Rebuild the object. See Corrupt Object File for more information.Linker Tools Error LNK1115/MACHINE option requiredLINK or LIB cannot determine the machine type for objects that are provided entirely from libraries. Either specify the /MACHINE option with the appropriate machine type or specify at least one object file in the input.Linker Tools Error LNK1117syntax error in option "option"The given option was not correctly specified.Linker Tools Error LNK1118syntax error in keyword statementThe given module-definition statement was not correctly specified.Linker Tools Error LNK1119invalid ordinal number "argument"The argument following the at sign (@) in an ordinal specification was not avalid number. An ordinal number is an optional argument in either an /EXPORToption in a LINK or LIB command or an EXPORTS statement in a moduledefinitionfile. It is an index into the exports table. The number must be aninteger in the range 1-65535.Linker Tools Error LNK1120number unresolved externalsLinker Tools Messages Page 5 of 37Error LNK1120 gives you a count (number) of unresolved externals for this link.The conditions that cause unresolved externals are described with errorLNK2001 (see Linker Errors LNK2001 to LNK2014), which precedes this error message (once for each unresolved external).Linker Tools Error LNK1121duplicate ordinal number "number"The given ordinal number was specified more than once in either an /EXPORT option in a LINK or LIB command or an EXPORTS statement in a moduledefinition file. Ordinal numbers must be unique integers in the range 1-65535.Linker Tools Error LNK1123failure during conversion to COFF: file invalid or corruptThe object or resource could not be converted to COFF. This tool requires the format of all input files to be COFF. If an input file is not COFF, the tool runs a conversion tool, either CVTOMF (to convert 32-bit OMF objects) or CVTRES (to convert resource files). This error is preceded by errors or warnings from the conversion tool. One of the following may be a cause:l The file is corrupt.l The file is not a valid file type. An example of an invalid type is a 16-bit OMF object.Linker Tools Error LNK1127library is corruptThe library file is corrupt. Rebuild the library.Linker Tools Error LNK1129cannot find resolution for weak extern symbolThe given weak external symbol does not have a default resolution. Probablythe symbol table is corrupt. Rebuild the object file. See Corrupt Object File for more information.Linker Tools Error LNK1130Linker miscalc (base relocations off by number)There was not enough space in the image to write base relocations.Linker Tools Error LNK1131no library file specifiedThe LIB /EXTRACT command required a library as input, but a library filenamewas not specified.Linker Tools Error LNK1132invalid format for MS-DOS stub file "filename"The filename specified with the /STUB option was not a valid real-mode MS-DOS executable (.EXE) file.Linker Tools Messages Page 6 of 37Linker Tools Error LNK1136invalid or corrupt fileThe input file either has a corrupt header or is zero size or abnormally small.See Corrupt Object File for more information.Linker Tools Error LNK1137invalid argument specified with /SECTIONEither the name or the attributes argument to the /SECTION option is specified incorrectly.Linker Tools Error LNK1140too many modules for program database; relink with /PDB:NONEThe project contains more than 4096 modules. One of the following is asolution:l Relink using /PDB:NONE.l Compile some modules without debugging information.l Reduce the number of modules.Linker Tools Error LNK1141failure during build of exports fileLINK could not build the exports (.EXP) file. Causes of this error include system problems such as insufficient memory and syntax errors in options or moduledefinition statements. This error is preceded by another error that givesadditional information.Linker Tools Error LNK1143invalid or corrupt file: no symbol for COMDAT section numberThe object file is corrupt. Rebuild the file. See Corrupt Object File for more information.Linker Tools Error LNK1144error with LINK_REPRO var; cannot open "filename"The linker could not create filename. One of the following may be a cause:l Check that you've set your LINK_REPRO environment variable to anexisting directory and not the current directory.l Make sure there are no read-only files in the directory.l Make sure none of the files in the LINK_REPRO directory are open byanother process, because the linker needs to write to them.Linker Tools Error LNK1145/MERGE created circular link for section "section"You attempted to merge a section into itself. Check the /MERGE options.Linker Tools Error LNK1146Linker Tools Messages Page 7 of 37no argument specified with option "option"The given option requires an argument.Linker Tools Error LNK1147invalid number specified with option "option"The argument to the given option was specified incorrectly.Linker Tools Error LNK1148failure during conversion to COFF: cannot copy temp file filenameEDITBIN could not convert the input file to COFF. When EDITBIN converts a file,it creates a temporary file, then copies the file. One of the following may be a cause: l The given file does not have the appropriate permissions.l There was not enough disk space to create the file.l The drive being written to was not available, possibly due to a network problem.Linker Tools Error LNK1149output filename matches input filename "filename"The output filename specified with the /OUT or /IMPLIB option was the same asan input file.Return to Main Linker Error PageLinker Errors LNK1152 to LNK1189Linker Tools Error LNK1152cannot resolve one or more undecorated symbolsThis error is preceded by one warning LNK4022 for each undecorated symbolthat could not be resolved and by at least two warnings LNK4006 for the duplicate symbols found for the undecorated symbol.Linker Tools Error LNK1153/VXD command-line option requiredYou attempted to build a virtual device driver without the /VXD option. Relinkwith the /VXD option.Linker Tools Error LNK1154specified import library filename matches exports file "filename"The filename specified with LINK /IMPORT or with LIB /DEF /OUT conflicted with the filename given by LINK or LIB to the exports file, which is formed from the base name of the main output file and the extension .EXP.Linker Tools Error LNK1155special symbol "symbol" already definedLinker Tools Messages Page 8 of 37The given symbol is reserved for use by LINK.Linker Tools Error LNK1156.sbss section not supportedAn object file contained an .sbss section.Linker Tools Error LNK1157fixup overflow; offset of target symbol "symbol" greater than +-8MBThe VXD is too large, or the sections are not arranged properly.Linker Tools Error LNK1158cannot run "filename"The given executable file called by LINK is not in the directory that contains LINK and is not in a directory specified in the PATH environment variable. Linker Tools Error LNK1159no output file specifiedNo name was specified for the main output file (executable file or DLL). LINK derives the default name of the output file from the base name of the first object file. If no object files are specified, and if the /OUT option is not used, this error occurs.Linker Tools Error LNK1160library with zero objects not allowedAn attempt was made to remove an object from a library that contained only that object. The object was not removed.Linker Tools Error LNK1161invalid export specificationEither the /EXPORT option or the EXPORTS module-definition statement incorrectly specified an export. A possible cause is a typing error.Linker Tools Error LNK1162expected aux symbol for comdat section numberThe linker expected to find an auxiliary symbol table for the indicated COMDAT but could not. The object file is probably corrupt. See Corrupt Object File for more information.Linker Tools Error LNK1163invalid selection for comdat section numberThe byte in the object file indicating the type of COMDAT section is invalid. The object file is probably corrupt. See Corrupt Object File for more information. Linker Tools Error LNK1164section section alignment (number) greater than /ALIGN valueThe alignment size for the given section in the object file exceeds the value specified with the /ALIGN option. The /ALIGN value must be a power of 2 and Linker Tools Messages Page 9 of 37must equal or exceed the section alignment given in the object file. Either recompile with a smaller section alignment or increase the /ALIGN value. Linker Tools Error LNK1165link failed because of fixup errorsThe build failed due to fixup errors. The /FORCE or /FORCE:UNRESOLVED option overrides this error.Linker Tools Error LNK1166cannot adjust code at offset=offset, va=valueLINK was unable to pad the code as required. Certain instructions are not allowed to cross page boundaries on some processors. LINK attempts to add pads to correct this situation. In this case, LINK could not work around the problem.Linker Tools Error LNK1167file contains relocs but header has no machine typeA converted COFF object did not have a machine type specified in its header. One cause of this error is omitting a machine type when converting a .RES file in a separate step before linking.Linker Tools Error LNK1168cannot open filename for writingThe given file does not have write permission.Linker Tools Error LNK1169one or more multiply defined symbols foundThe build failed due to multiple definitions of one or more symbols. This error is preceded by error LNK2005. The /FORCE or /FORCE:MULTIPLE option overrides this error.Linker Tools Error LNK1170line in command file contains limit or more charactersThe length of a line in a command file must be less than the given limit.Linker Tools Error LNK1171unable to load filenameThe given DLL was unavailable. The possible locations for the DLL are the current directory, the system directory, the Windows directory, and the directories specified in the PATH environment variable.Linker Tools Error LNK1172more than one object with the name "object" found; rename object(s) or relink /PDB:NONEA library contained two or more objects with the same name. Do one of the following:Linker Tools Messages Page 10 of 37l Rename the objects using unique names and rebuild the library.l Link using the /PDB:NONE option.Linker Tools Error LNK1173unable to find entrypoint function in filenameThe given function does not exist in the given DLL.Linker Tools Error LNK1174unable to /REBASE filename; not a valid Win32 imageThe format of the given file was invalid.Linker Tools Error LNK1175failed to /REBASE filenameThe rebase operation failed on the given file.Linker Tools Error LNK1177TOC size limit exceededThe linker was unable to create a TOC (Table of Contents) in your image file. The limit is 2048 entries in the TOC.Linker Tools Error LNK1178missing MODEND record; file is invalid or corruptThe linker tool tried to convert an OMF object module to COFF format but could not find an expected MODEND (module end) record in the OMF object. The OMF object module is corrupt and needs to be recreated or recopied. See Corrupt Object File for more information.Linker Tools Error LNK1179invalid or corrupt file: duplicate comdat comdatAn object module contained two or more COMDATs with the same name. One possible cause is if you use the Visual C++ /H option with the Visual C++ /Gy option. The /H option limits the length of external names, and the /Gy option packages functions in COMDATs.Linker Tools Error LNK1180insufficient disk space to complete linkThe linker tool was unable to complete a file operation since the operating system reported that the disk is full. Free up space on your local and network drives (if you are writing files there).Linker Tools Error LNK1181cannot open input file "filename"The linker tool could not find "filename" because it does not exist or the path was not found.Linker Tools Error LNK1182Linker Tools Messages Page 11 of 37cannot have more than 64K exportsYou have reached the linker's limit of 65,536 exports.Linker Tools Error LNK1183invalid or corrupt file: extended relocation count number less than 65535The COFF object file is corrupt since it contains an extended relocation count that is less than 0xFFFF. See Corrupt Object File for more information.Linker Tools Error LNK1184invalid section name "section" specified in option or directive "option"You gave the linker an invalid section name in option. Invalid section names contain "$" or blanks.Linker Tools Error LNK1185invalid section name "section" specifiedYou gave the linker an invalid section name in a .DEF file. Invalid section names contain "$" or blanks.Linker Tools Error LNK1186invalid or corrupt COFF object; reloc to undefined static symbol "symbol"Your COFF object module is corrupt since it contains a relocation entry for an undefined static symbol. See Corrupt Object File for more information.Linker Tools Error LNK1187Corrupt object - unmatched name relocation; ignoredYour object file contains bad relocation information. Recopy or recreate the object file. See Corrupt Object File for more information.Linker Tools Error LNK1188BADFIXUPSECTION:: invalid fixup target "symbol"; possible zero length section This message is issued only for VxD links when the target of a relocation does not have a section. With LINK386 (an older version), an OMF GROUP record (generated by a MASM GROUP directive) may have been used to combine the zero length section with another non-zero length section. COFF format does not support the GROUP directive and zero-length sections. When LINK automatically converts this type of OMF objects to COFF, this error may occur.Linker Tools Error LNK1189LIBTOOMANYMEMBERS:: library limit of number objects exceededThe limit of 65535 objects or members in a library has been exceeded.Return to Main Linker Error PageLinker Errors LNK1190 to LNK1581Linker Tools Error LNK1190Linker Tools Messages Page 12 of 37invalid fixup found, type typeThe object file has become corrupted. Recompile.Linker Tools Error LNK1194cannot delay-load dll name due to import of data symbol symbol name; relink without /DELAYLOAD:dll nameYou cannot delay load a DLL if data is imported from it.Linker Tools Error LNK1195target machine "machine" requires "option"Add the required option.Linker Tools Error LNK1196invalid or corrupt import object: unknown versionThe import library has become corrupted. Rebuild the library.Linker Tools Error LNK1197invalid or corrupt import object: unknown typeThe import library has become corrupted. Rebuild the library.Linker Tools Error LNK1198invalid or corrupt import object: unknown name typeThe import library has become corrupted. Rebuild the library.Linker Tools Error LNK1199invalid or corrupt import object: non-zero reserved fieldsThe import library has become corrupted. Rebuild the library.Linker Tools Error LNK1200error reading program database "filename"The given program database (PDB) could not be read, probably because it is corrupted. If filename is the PDB for an object file, recompile the object file; use the /debug:full and /pdbfile options. If filename is the PDB for the main outputfile and this error occurred during an incremental link, delete the PDB and relink.Linker Tools Error LNK1201error writing to program database "filename"; check for insufficient disk space LINK could not write to the program database (PDB) for the output file. One of the following may be a cause:l The file is corrupted. Delete filename and relink.l There was not enough disk space to write to the file.l The drive being written to was not available, possibly due to a network problem.Linker Tools Error LNK1202Linker Tools Messages Page 13 of 37"filename" missing debugging information for referencing moduleThe given program database (PDB) for an object file was invalid. Recompile the object file; use CL's /Zi option.Linker Tools Error LNK1203"filename" missing current debugging information for referencing module The given program database (PDB) for an object file was invalid. Recompile the object file; use CL's /Zi option.Linker Tools Error LNK1204"filename" compiled /Yc /Yu /Z7; cannot create PDB; recompile with /Zi Multilayered program databases (PDBs) are not supported in combination with old-style debugging information. Recompile using CL's /Zi option.Linker Tools Error LNK1206cannot overwrite Visual C++ 1.0 PDB "filename"; delete and rebuildThis version of LINK cannot write to an existing program database (PDB) created using older versions of the visual development environment. Delete filename and rebuild.Linker Tools Error LNK1207incompatible PDB format in "filename"; delete and rebuildThis version of LINK cannot write to the existing program database (PDB). Delete filename and rebuild.Linker Tools Error LNK1209program database "filename" differs from previous link; relink or rebuildThe given program database (PDB) is invalid and possibly corrupt. Relink. If filename is also the PDB for an object file, recompile to recreate the PDB. Linker Tools Error LNK1210insufficient memory for incremental link; relink with /INCREMENTAL:NO There was not enough virtual memory available for LINK to create the incremental status (.ILK) file.Linker Tools Error LNK1211precompiled type information not found; "filename" not linked or overwritten The given object file, compiled with /Yc, either was not specified in the LINK command or was overwritten.Linker Tools Error LNK1212error opening program database; file is in useThe PDB is already in use by another application.Linker Tools Error LNK1213unexpected import object encounteredThe import library has become corrupted. Rebuild the library.Linker Tools Messages Page 14 of 37Linker Tools Error LNK1221a subsystem can't be inferred and must be definedThe linker does not have enough information to infer which subsystem you will target your application. To fix this error, use the /SUBSYSTEM option.Linker Tools Error LNK1561entry point must be definedThe symbol specified by the /ENTRY option is not defined.Linker Tools Error LNK1581corrupted object or old compiler (bad Pcode entry point)Your object file contained a bad entry point. The object file is probably corrupt.。
fortran常见错误代码If you have installed the Parallel Software Environment and compiled a program for parallel execution, additional messages specific to parallel execution may appear (see the DIGITAL High Performance Fortran 90 HPF and PSE Manual).statement specified STATUS= 'NEW '(create new file) using I/O unit x. Make sure correct file name, directory path, unit, and so forth were specified in the source program. Decide whether to:Rename or remove the existing file before rerunning theprogram.Modify the source file to specify different filespecification, I/O unit, or OPEN statement STATUS.severe (19): Invalid reference to variable in NAMELIST inputFOR$IOS_INVREFVAR. One of the following conditions occurred: 19The variable was not a member of the namelist group.An attempt was made to subscript a scalar variable.A subscript of the array variable was out-of-bounds. An array variable was specified with too many or too few subscripts for the variable.An attempt was made to specify a substring of a noncharacter variable or array name.A substring specifier of the character variable wasout-of-bounds.A subscript or substring specifier of the variable was not an integer constant.An attempt was made to specify a substring by using an unsubscripted array variable.20 severe (20): REWIND errorFOR$IOS_REWERR. One of the following conditions occurred:The file was not a sequential file.The file was not opened for sequential or append access. The DIGITAL Fortran 90 RTL I/O system detected an error condition during execution of a REWIND statement.severe (24): End-of-file during readFOR$IOS_ENDDURREA. One of the following conditions occurred:A DIGITAL Fortran 90 RTL I/O system end-of-file conditionwas encountered during execution of a READ statement that did not contain an END, ERR, or IOSTAT specification.An end-of-file record written by the ENDFILE statement was encountered during execution of a READ statement that did not contain an END, ERR, or IOSTAT specification.An attempt was made to read past the end of an internal file character string or array during execution of a READ statement that did not contain an END, ERR, or IOSTATspecification.This error is returned by END and ERRSNS.27 severe (27): Too many records in I/O statementFOR$IOS_TOOMANREC. An attempt was made to do one of the following: Read or write more than one record with an ENCODE or DECODEstatement.Write more records than existed.condition is not one of the more common conditions for which specific error messages are provided. It can occur when an OPEN operation was attempted for one of the following:Segmented file that was not on a disk or a raw magnetic tape Standard I/O file that had been closed31 severe (31): Mixed file access modesFOR$IOS_MIXFILACC. An attempt was made to use any of the following combinations:Formatted and unformatted operations on the same unit An invalid combination of access modes on a unit, such as direct and sequentialA DIGITAL Fortran 90 RTL I/O statement on a logical unit that was opened by a program coded in another language33severe (33): ENDFILE errorFOR$IOS_ENDFILERR. One of the following conditions occurred: The file was not a sequential organization file with variable-length records.The file was not opened for sequential or append access.An unformatted file did not contain segmented records. The DIGITAL Fortran 90 RTL I/O system detected an error during execution of an ENDFILE statement.severe (46): Inconsistent OPEN/CLOSE parametersFOR$IOS_INCOPECLO. Specifications in an OPEN or CLOSE statement 46were inconsistent. Some invalid combinations follow:READONLY or ACTION= 'READ 'with STATUS= 'NEW 'or STATUS='SCRATCH 'READONLY with STATUS= 'REPLACE ', ACTION= 'WRITE ', or ACTION= 'READWRITE 'ACCESS= 'APPEND 'with READONLY, ACTION= 'READ ', STATUS= 'NEW ', or STATUS= 'SCRATCH ' DISPOSE= 'SAVE ', 'PRINT ', or 'SUBMIT 'with STATUS= 'SCRATCH 'DISPOSE= 'DELETE 'with READONLYCLOSE statement STATUS= 'DELETE 'with OPEN statement READONLYACCESS= 'APPEND 'with STATUS= 'REPLACE 'ACCESS= 'DIRECT 'or 'KEYED 'with POSITION= 'APPEND ', 'ASIS ', or 'REWIND 'error (75): Floating point exceptionFOR$IOS_SIGFPE. A floating-point exception occurred. Core dump file created. Possible causes include: Division by zeroOverflowInvalid operation, such as subtraction of infinite values, multiplication of zero by infinity (without signs), division of zero by zero or infinity by infinityConversion of floating-point to fixed-point format when an overflow prevents conversioninfo (95): Floating-point conversion failedFOR$IOS_FLOCONFAI. The attempted unformatted read or write of nonnative floating-point data failed because the floating-point value:Exceeded the allowable maximum value for the equivalentnative format and was set equal to infinity (plus or minus) Was infinity (plus or minus) and was set to infinity (plus or minus) Was invalid and was set to not a number (NaN)Very small numbers are set to zero (0). This error could be caused by the specified nonnative floating-point format not matching the floating-point format found in the specified file.Check the following:The correct file was specified.The record layout matches the format DIGITAL Fortran 90 is expecting.The ranges for the data being used (Chapter 9)The correct nonnative floating-point data format wasspecified (Chapter 10).。
常见fortran错误1. Incrementally linked image--PC correlation disabled.!编译终止2. forrtl: severe (157): Program Exception - access violation!The program tried to read from or write to a virtual address for which it does not have the appropriate access. Try recompiling with the /check:bounds and /warn:argument_checking options set, to see if the problem is an out-of-bounds memory reference or a argument mismatch that causes data to be treated as an address.Other causes of this error include:Mismatches in C vs. STDCALL calling mechanisms, causing the stack to become corrupted References to unallocated pointers Attempting to access a protected (for example, read-only) address3 "forrtl: severe (64): input conversion error, unit 2, file D:\FORTRAN2\testi!文件testi正在读写,直到读写到2时错误。
举例:程序想读写整数,却碰到变量故终止。
4 error LNKZOOI : unresolved external symbol _ SN @ 4 fatal error LNKllZO : 1 unresolved externals! 出现了未指定的外部函数符号Sn 。
fortran里minloc的使用-回复Fortran is a programming language commonly used in scientific and engineering applications. One useful function in Fortran is`minloc`, which allows programmers to find the position of the smallest element in an array. In this article, we will explore the various aspects of using `minloc` in Fortran, step by step.1. Introduction to `minloc`:The `minloc` function in Fortran returns the position of the smallest element in an array, along with its value. The function is defined as `minloc(array, dim, mask)` where `array` is the input array, `dim` specifies the dimension along which the minimum value is sought, and `mask` is an optional argument that allows selective searching.2. Basic usage:The simplest usage of `minloc` involves finding the index of the smallest element in an array along a given dimension. For example, consider the following array `A`:fortranreal :: A(3) = [5.0, 2.0, 7.0]To find the position of the smallest element, we can write:fortranminloc_index = minloc(A)In this case, `minloc_index` will be equal to 2, corresponding to the index of the element with value 2.0.3. Specifying the dimension:In Fortran, arrays can be multidimensional. To find the minimum value along a specific dimension, we need to specify the `dim` argument. For instance, consider a two-dimensional array `B`: fortranreal :: B(2, 3) = reshape([1.0, 4.0, 3.0, 2.0, 7.0, 5.0], [2, 3])If we want to find the position of the smallest element along the first dimension (rows), we can write:fortranminloc_index = minloc(B, dim=1)Here, `minloc_index` will be an array of size 2, containing the indices of the smallest elements for each row.4. Selective searching using the mask:The `mask` argument in `minloc` allows us to perform selective searching for the minimum value based on certain conditions. This can be useful when dealing with large arrays or complex data structures. Suppose we have an array `C` with both positive and negative values:fortranreal :: C(4) = [-1.0, 3.0, -2.0, 4.0]To find the position of the smallest positive element, we can define a mask based on a logical condition:fortranmask = C > 0.0minloc_index = minloc(C, mask=mask)In this case, `minloc_index` will be equal to 2, corresponding to the index of the positive element with the smallest value.5. Handling tie-breakers:In some cases, the array may contain multiple elements with the same minimum value. By default, `minloc` returns the first occurrence. However, we can specify the `back` optional argumentto change this behavior. For example, consider an array `D` with multiple occurrences of the smallest element:fortranreal :: D(5) = [2.0, 1.0, 3.0, 1.0, 4.0]To obtain the last occurrence of the smallest element, we can write:fortranminloc_index = minloc(D, back=.true.)Here, `minloc_index` will be equal to 4, corresponding to the index of the last occurrence of the smallest element.6. Handling arrays with zero elements:If the array passed to `minloc` contains zero elements, the function returns an array of zeros. To handle this, we can check the size of the result and take appropriate actions if necessary. For example:fortranif (size(minloc_index) == 0) then! Handle the case when the array is empty...else! Process the result...endifIn summary, the `minloc` function in Fortran is a powerful tool for finding the position of the smallest element in an array. By specifying the desired dimension and using the optional `mask` and `back` arguments, programmers can perform advanced searching and handle various scenarios. Understanding and utilizing `minloc` can greatly enhance the functionality and efficiency of Fortran programs.。
fortran用法总结我的Fortran基本用法小结周日, 10/14/2007 - 21:00 — gator一、说明二、概述三、数据类型及基本输入输出四、流程控制五、循环六、数组七、函数八、文件一、说明本文多数内容是我读彭国伦《Fortran 95 程序设计》的笔记。
只读到第九章,主要是3~9章,都是最基本的用法(原书共16章)。
这里主要摘录了我看书过程中总结的一些Fortran和C不同的地方,主要是语法方面。
希望这份笔记能够给学过C但没有接触过Fortran的同学带去一些帮助。
要想得更清楚些,推荐看一下原书,觉得作者真的写得很好,很清楚;如果有C语言的基础,看完前九应该很快的,花一两天就行了。
觉得如果耐心看完本文,基本功能应该也可以顺利用起来了。
外,由于我之前没有用过Fortran,这次为了赶文档看书又看得很粗浅,大多数东西看过之后都没得及仔细想,只是按着作者的意思去理解。
所以这份笔记还处于纸上谈兵的层次。
如果有不妥的方,希望大家指正。
谢谢!文中蓝色的部分是程序代码,!后面的内容为注释。
二、概述1、名词解释Fortran=For mula Tran slator/Translation一看就知道有什么特色了:可以把接近数学语言的文本翻译成机械语言。
的确,从一开始,IBM设计的时候就是为了方便数值计算和科学数据处理。
设计强大的数组操作就是为了实现这一目标。
ortran奠定了高级语言发展的基础。
现在Fortran在科研和机械方面应用很广。
2、Fortran的主要版本及差别按其发展历史,Fortran编译器的版本其实很多。
现在在广泛使用的是Fortran 77和Fortran90。
ortran 90在Fortran 77基础上添加了不少使用的功能,并且改良了77编程的版面格式,所以编程时推荐使用90。
鉴于很多现成的程序只有77版本,有必要知道77的一些基本常识,至少保证能够看77程序。
以下是77和90的一些格式上的区别。
If you have installed the Parallel Software Environment and compiled a program for parallel execution, additional messages specific to parallel execution may appear (see the DIGITAL High Performance Fortran 90 HPF and PSE Manual).statement specified STATUS= 'NEW '(create new file) using I/O unit x. Make sure correct file name, directory path, unit, and so forth were specified in the source program. Decide whether to:Rename or remove the existing file before rerunning theprogram.Modify the source file to specify different filespecification, I/O unit, or OPEN statement STATUS.severe (19): Invalid reference to variable in NAMELIST inputFOR$IOS_INVREFVAR. One of the following conditions occurred: 19The variable was not a member of the namelist group.An attempt was made to subscript a scalar variable.A subscript of the array variable was out-of-bounds. An array variable was specified with too many or too few subscripts for the variable.An attempt was made to specify a substring of a noncharacter variable or array name.A substring specifier of the character variable wasout-of-bounds.A subscript or substring specifier of the variable was not an integer constant.An attempt was made to specify a substring by using an unsubscripted array variable.20 severe (20): REWIND errorFOR$IOS_REWERR. One of the following conditions occurred:The file was not a sequential file.The file was not opened for sequential or append access. The DIGITAL Fortran 90 RTL I/O system detected an error condition during execution of a REWIND statement.severe (24): End-of-file during readFOR$IOS_ENDDURREA. One of the following conditions occurred:A DIGITAL Fortran 90 RTL I/O system end-of-file conditionwas encountered during execution of a READ statement that did not contain an END, ERR, or IOSTAT specification.An end-of-file record written by the ENDFILE statement was encountered during execution of a READ statement that did not contain an END, ERR, or IOSTAT specification.An attempt was made to read past the end of an internal file character string or array during execution of a READstatement that did not contain an END, ERR, or IOSTATspecification.This error is returned by END and ERRSNS.27 severe (27): Too many records in I/O statementFOR$IOS_TOOMANREC. An attempt was made to do one of the following: Read or write more than one record with an ENCODE or DECODEstatement.Write more records than existed.condition is not one of the more common conditions for which specific error messages are provided. It can occur when an OPEN operation was attempted for one of the following:Segmented file that was not on a disk or a raw magnetic tape Standard I/O file that had been closed31 severe (31): Mixed file access modesFOR$IOS_MIXFILACC. An attempt was made to use any of the following combinations:Formatted and unformatted operations on the same unit An invalid combination of access modes on a unit, such as direct and sequentialA DIGITAL Fortran 90 RTL I/O statement on a logical unit that was opened by a program coded in another language33severe (33): ENDFILE errorFOR$IOS_ENDFILERR. One of the following conditions occurred: The file was not a sequential organization file with variable-length records.The file was not opened for sequential or append access.An unformatted file did not contain segmented records. The DIGITAL Fortran 90 RTL I/O system detected an error during execution of an ENDFILE statement.severe (46): Inconsistent OPEN/CLOSE parametersFOR$IOS_INCOPECLO. Specifications in an OPEN or CLOSE statement 46were inconsistent. Some invalid combinations follow:READONLY or ACTION= 'READ 'with STATUS= 'NEW 'or STATUS='SCRATCH 'READONLY with STATUS= 'REPLACE ', ACTION= 'WRITE ', or ACTION= 'READWRITE 'ACCESS= 'APPEND 'with READONLY, ACTION= 'READ ', STATUS= 'NEW ', or STATUS= 'SCRATCH 'DISPOSE= 'SAVE ', 'PRINT ', or 'SUBMIT 'with STATUS= 'SCRATCH 'DISPOSE= 'DELETE 'with READONLYCLOSE statement STATUS= 'DELETE 'with OPEN statement READONLYACCESS= 'APPEND 'with STATUS= 'REPLACE 'ACCESS= 'DIRECT 'or 'KEYED 'with POSITION= 'APPEND ', 'ASIS ', or 'REWIND 'error (75): Floating point exceptionFOR$IOS_SIGFPE. A floating-point exception occurred. Core dump file created. Possible causes include:Division by zeroOverflowInvalid operation, such as subtraction of infinite values, multiplication of zero by infinity (without signs),division of zero by zero or infinity by infinityConversion of floating-point to fixed-point format when an overflow prevents conversioninfo (95): Floating-point conversion failedFOR$IOS_FLOCONFAI. The attempted unformatted read or write of nonnative floating-point data failed because the floating-point value:Exceeded the allowable maximum value for the equivalentnative format and was set equal to infinity (plus or minus) Was infinity (plus or minus) and was set to infinity (plus or minus)Was invalid and was set to not a number (NaN)Very small numbers are set to zero (0). This error could be caused by the specified nonnative floating-point format not matching the floating-point format found in the specified file.Check the following:The correct file was specified.The record layout matches the format DIGITAL Fortran 90 is expecting.The ranges for the data being used (Chapter 9)The correct nonnative floating-point data format wasspecified (Chapter 10).。
Fortran2003extensions and the NAG Fortran CompilerNovember21,20081IntroductionThis document describes those parts of the Fortran2003language which are not in Fortran95,and indicates which features are currently supported by the NAG Fortran Compiler.Features marked in the section heading as‘[5.2]’are newly available in release5.2,those marked‘[5.1]’were available in release5.1(and in some cases earlier),and those marked‘[n/a]’are not yet available.2Overview of Fortran2003Fortran2003is a major advance over Fortran95:the new language features can be grouped as follows:•object-oriented programming features,•allocatable attribute extensions,•other data-oriented enhancements,•interoperability with C,•IEEE arithmetic support,•input/output enhancements and•miscellaneous enhancements.The basic object-oriented features are type extension,polymorphic variables,and type selection;these provide in-heritance and the ability to program ad-hoc polymorphism in a type-safe manner.The advanced features are typed allocation,cloning,type-bound procedures,type-bound generics,and object-bound procedures.Type-bound proce-dures provide the mechanism for dynamic dispatch(methods).The ALLOCATABLE attribute is extended to allow it to be used for dummy arguments,function results,structure components,and scalars(not just arrays).An intrinsic procedure has been added to transfer an allocation from one variable to another.Finally,in intrinsic assignment,allocatable variables or components are automatically reallocated with the correct size if they have a different shape or type parameter value from that of the expression.This last feature,together with deferred character length,provides the user with true varying-length character variables. There are two other major data enhancements:the addition of type parameters to derived types,andfinalisation(by final subroutines).Other significant data enhancements are the PROTECTED attribute,pointer bounds specification and rank remapping,procedure pointers,and individual accessibility control for structure components.Interoperability with the C programming language consists of allowing C procedures to be called from Fortran,Fortran procedures to be called from C,and for the sharing of global variables between C and Fortran.This can only happen where C and Fortran facilities are equivalent:an intrinsic module provides derived types and named constants for mapping Fortran and C types,and the BIND(C)syntax is added for declaring Fortran entities that are to be shared with C.Additionally,C style enumerations have been added.Support for IEEE arithmetic is provided by three intrinsic e of the IEEE FEATURES module requests IEEE compliance for specific Fortran features,the IEEE EXCEPTIONS module provides access to IEEE modes and exception handling,and the IEEE ARITHMETIC module provides enquiry functions and utility functions for determining the extent of IEEE conformance and access to IEEE-conformant facilities.The input/output facilities have had three major new features:asynchronous input/output,stream input/output, and user-defined procedures for derived-type input/output(referred to as“defined input/output”).Additionally,the input/output specifiers have been regularised so that where they make sense:all specifiers that can be used on an OPEN statement can also be used on a READ or WRITE statement,and vice versa.Access to input/output error messagesis provided by the new IOMSG=specifier,and processor-dependent constants for input/output(e.g.the unit number for the standard inputfile)are provided in a new intrinsic module.Finally,there are a large number of miscellaneous improvements in almost every aspect of the language.Some of the more significant of these are the IMPORT statement(provides host association into interface blocks),the VALUE and VOLATILE attributes,the ability to use all intrinsic functions in constant expressions,and extensions to the syntax of array and structure constructors.3Object-oriented programming3.1Type ExtensionType extension provides thefirst phase of object orientation:inheritance and polymorphic objects.3.1.1Extending Types[5.0]Any derived type can be extended using the EXTENDS keyword,except for SEQUENCE types and BIND(C)types. (The latter types are“non-extensible”,as are intrinsic types,whereas all other derived types are“extensible”.)The extended type inherits all the components of the parent type and may add extra components.For example:TYPE pointREAL x,yEND TYPETYPE,EXTENDS(point)::point_3dREAL zEND TYPEThe type point3d has x,y and z components.Additionally,it has a point component which refers to the inher-ited part;this“parent component”is“inheritance-associated”with the inherited components,so that the point%x component is identical to the x component et cetera.However,when extending a type it is not required to add any new components;for example,TYPE,EXTENDS(point)::newpointEND TYPEdefines a new type newpoint which has exactly the same components as point(plus the associated parent component). Similarly,it is no longer necessary for a type to contain any components:TYPE empty_typeEND TYPEdeclares the extensible(but not extended)type empty type which has no components at all.3.1.2Polymorphic Variables[5.0]A polymorphic variable is a pointer,allocatable array or dummy argument that is declared using the CLASS keyword instead of the TYPE keyword.A CLASS(typename)variable can assume any type in the class of types consisting of TYPE(typename)and all extensions of typename.For example:REAL FUNCTION bearing(a)CLASS(point)abearing=atan2(a%y,a%x)ENDThe function bearing may be applied to a TYPE(point)object or to a TYPE(point3d)object,or indeed to an object of any type that is an extension of TYPE(point).3.1.3Type Selection[5.0]The SELECT TYPE construct provides both a means of testing the dynamic type of a polymorphic variable and access to the extended components of that variable.For example:CLASS(t)x...SELECT TYPE(p=>x)TYPE IS(t1)!!This section is executed only if X is exactly of TYPE(t1),not an!extension thereof.P is TYPE(t1).!TYPE IS(t2)!!This section is executed only if X is exactly of TYPE(t2),not an!extension thereof.P is TYPE(t2).!CLASS IS(t3)!!This section is executed if X is of TYPE(t3),or of some extension!thereof,and if it is not caught by a more specific case.P is CLASS(t3).!END SELECTNote that‘SELECT TYPE(x)’is short for‘SELECT TYPE(x=>x)’.3.1.4Unlimited polymorphism[5.2]A variable that is‘CLASS(*)’is an unlimited polymorphic variable.It has no type,but can assume any type including non-extensible types and intrinsic types(and kinds).Apart from allocation,deallocation and pointer assignment, to perform any operation on an unlimited polymorphic youfirst have to discover its type using SELECT TYPE.For example:CLASS(*),POINTER::xCHARACTER(17),TARGET::chx=>chSELECT TYPE(x)TYPE IS(COMPLEX(KIND=KIND(0d0)))PRINT*,x+1TYPE IS(CHARACTER(LEN=*))PRINT*,LEN(x)END SELECTNote that in the case of CHARACTER the length must be specified as‘*’and is automatically assumed from whatever the polymorphic is associated with.In the case of a non-extensible(i.e.BIND(C)or SEQUENCE)type,SELECT TYPE cannot be used to discover the type; instead,an unsafe pointer assignment is allowed,for example:TYPE tSEQUENCEREAL xEND TYPECLASS(*),POINTER::xTYPE(t),POINTER::y...y=>x!Unsafe-the compiler cannot tell whether X is TYPE(t).3.1.5Ad hoc type comparison[n/a]Two new intrinsic functions are provided for comparing the dynamic types of polymorphic objects.These areEXTENDS TYPE OF(A,MOLD)SAME TYPE AS(A,B)The arguments must be objects of extensible types(though they need not be polymorphic).SAME TYPE AS returns .TRUE.if and only if both A and B have the same dynamic type.EXTENDS TYPE OF returns.TRUE.if and only if the dynamic type of A is the same as,or an extension of,the dynamic type of MOLD.Note that if MOLD is an unallocated unlimited polymorphic(CLASS(*)),the result will be true regardless of the state of A.The arguments are permitted to be unallocated or disassociated,but they are not permitted to be pointers with an undefined association status.It is recommended that where possible these intrinsic functions be avoided,and that SELECT TYPE be used for type checking instead.3.2Typed allocation[5.1]The ALLOCATE statement now accepts a type-spec;this can be used to specify the dynamic type(and type parameters, if any)of an allocation.The type-spec appears before the allocation list,and is separated from it by a double colon. For example,if T is an extensible type and ET is an extension of T,CLASS(t),POINTER::a(:)ALLOCATE(et::a(100))allocates A to have dynamic type ET.Note that the type-spec in an ALLOCATE statement omits the TYPE keyword for derived types,similarly to the TYPE IS and CLASS IS statements.An unlimited polymorphic object can be allocated to be any type including intrinsic types:for exampleCLASS(*),POINTER::c,dALLOCATE(DOUBLE PRECISION::c)READ*,nALLOCATE(CHARACTER(LEN=n)::d)allocates C to be double precision real,and D to be of type CHARACTER with length N.Typed allocation is only useful for allocating polymorphic variables and CHARACTER variables with deferred length (LEN=:).For a non-polymorphic variable,the type-spec must specify the declared type and,if it is type CHARACTER but not deferred-length,to have the same character length.The character length must not be specifed as an asterisk (CHARACTER(LEN=*))unless the allocate-object is a dummy argument with an asterisk character length(and vice versa).Finally,since there is only one type-spec it must be compatible with all the items in the allocation list.3.3Sourced allocation(cloning)[5.1]The ALLOCATE statement now accepts the SOURCE=specifier.The dynamic type and value of the allocated entity is taken from the expression in the specifier.If the derived type has type parameters(q.v.),the value for any deferred type parameter is taken from the source expression,and the values for other type parameters must agree.This is not just applicable to derived types:if the entity being allocated is type CHARACTER with deferred length(LEN=:),the character length is taken from the source expression.Only one entity can be allocated when the SOURCE=specifier is used.Note that when allocating an array the array shape is not taken from the source expression but must be specified in the usual way.If the source expression is an array,it must have the same shape as the array being allocated.For example,CLASS(*),POINTER::a,b...ALLOCATE(a,SOURCE=b)The allocated variable A will be a“clone”of B,whatever the current type of B happens to be.3.4Type-bound procedures[5.1]Type-bound procedures provide a means of packaging operations on a type with the type itself,and also for dynamic dispatch to a procedure depending on the dynamic type of a polymorphic variable.3.4.1The type-bound procedure partThe type-bound procedure part of a type definition is separated from the components by the CONTAINS statement. The default accessibility of type-bound procedures is public even if the components are private;this may be changed by using the PRIVATE statement after the CONTAINS.3.4.2Specific type-bound proceduresThe syntax of a specific,non-deferred,type-bound procedure declaration is:PROCEDURE[[,binding-attr-list]::]binding-name[=>procedure-name]The name of the type-bound procedure is binding-name,and the name of the actual procedure which implements it is procedure-name.If the optional=>procedure-name is omitted,the actual procedure has the same name as the binding.A type-bound procedure is invoked via an object of the type,e.g.CALL variable(i)%tbp(arguments)Normally,the invoking variable is passed as an extra argument,the“passed-object dummy argument”;by default this is thefirst dummy argument of the actual procedure and so thefirst argument in the argument list becomes the second argument,etc.The passed-object dummy argument may be changed by declaring the type-bound procedure with the PASS(argument-name)attribute,in which case the variable is passed as the named argument.The PASS attribute may also be used to confirm the default(as thefirst argument),and the NOPASS attribute prevents passing the object as an argument at all.The passed-object dummy argument must be a polymorphic scalar variable of that type,e.g.CLASS(t)self.When a type is extended,the new type either inherits or overrides each type-bound procedure of the old type.An overriding procedure must be compatible with the old procedure;in particular,each dummy argument must have the same type except for the passed-object dummy argument which must have the new type.A type-bound procedure that is declared to be NON OVERRIDABLE cannot be overridden during type extension.When a type-bound procedure is invoked,it is the dynamic type of the variable which determines which actual procedure to call.The other attributes that a type-bound procedure may have are PUBLIC,PRIVATE,and DEFERRED(the latter only for abstract types,which are described later).3.4.3Generic type-bound proceduresA generic type-bound procedure is a set of specific type-bound procedures,in the same way that an ordinary generic procedure is a set of specific ordinary procedures.It is declared with the GENERIC statement,e.g.GENERIC::generic_name=>specific_name_1,specific_name_2,specific_name_3Generic type-bound procedures may also be operators or assignment,e.g.GENERIC::OPERATOR(+)=>add_t_t,add_t_r,add_r_tSuch type-bound generic operators cannot have the NOPASS attribute;the dynamic type of the passed-object dummy argument determines which actual procedure is called.When a type is extended,the new type inherits all the generic type-bound procedures without exception,and the new type may extend the generic with additional specific procedures.To override procedures in the generic,simply override the specific type-bound procedure.For example,inTYPE mycomplex...CONTAINSPROCEDURE::myc_plus_r=>myc1_plus_rPROCEDURE,PASS(B)::r_plus_myc=>r_plus_myc1GENERIC::OPERATOR(+)=>myc_plus_r,r_plus_mycEND TYPE...TYPE,EXTENDS(mycomplex)::mycomplex_2...CONTAINSPROCEDURE::myc_plus_r=>myc2_plus_rPROCEDURE,PASS(B)::r_plus_myc=>r_plus_myc2END TYPEthe type mycomplex2inherits the generic operator‘+’;invoking the generic(+)invokes the specific type-bound proce-dure,which for entities of type mycomplex2will invoke the overriding actual procedure(myc2plus r or r plus myc2).3.5Abstract derived types[5.1]An extensible derived type can be declared to be ABSTRACT,e.g.TYPE,ABSTRACT::mytypeAn abstract type cannot be instantiated;i.e.it is not allowed to declare a non-polymorphic variable of abstract type, and a polymorphic variable of abstract type must be allocated to be a non-abstract extension of the type.Abstract type may contain DEFERRED type-bound procedures,e.g....CONTAINSPROCEDURE(interface_name),DEFERRED::tbpnameNo binding(“=>name”)is allowed or implied by a deferred procedure binding.The interface name must be the name of an abstract interface or a procedure with an explicit interface,and defines the interface of the deferred type-bound procedure.When extending an abstract type,the extended type must also be abstract unless it overrides all of the deferred type-bound procedures with normal bindings.3.6Object-bound procedures[5.2]These are procedure pointer components,and act similarly to type-bound procedures except that the binding is per-object not per-type.The syntax of a procedure pointer component declaration is:PROCEDURE([proc-interface]),proc-component-attr-spec-list::proc-decl-listwhere•each proc-component-attr-spec is one of NOPASS,PASS,PASS(arg-name),POINTER,PRIVATE or PUBLIC,and •each proc-decl is a component name optionally followed by default initialisation to null(‘=>NULL()’).The POINTER attribute is required.Note that object-bound procedures have a passed-object dummy argument just like type-bound procedures;if this is not wanted,the NOPASS attribute must be used(and this is required if the interface is implicit,i.e.when proc-interface is missing or is a type specification).The following example demonstrates using a list of subroutines with no arguments.TYPE action_listPROCEDURE(),NOPASS,POINTER::action=>NULL()TYPE(action_list),POINTER::nextEND TYPETYPE(t),TARGET::topTYPE(t),POINTER::pEXTERNAL sub1,sub2top%action=sub1ALLOCATE(top%next)top%next%action=sub2...p=>topDO WHILE(ASSOCIATED(p))IF(ASSOCIATED(p%action))CALL p%actionp=>p%nextEND DO4ALLOCATABLE extensionsIn Fortran2003the ALLOCATABLE attribute is permitted not just on local variables but also on components,dummy variables,and function results.These are the same as described in the ISO Technical Report ISO/IEC TR15581:1999. Also,the MOVE ALLOC intrinsic subroutine has been added,as well as automatic reallocation on assignment.4.1Allocatable Dummy Arrays[4.x]A dummy argument can be declared to be an allocatable array,e.g.SUBROUTINE s(dum)REAL,ALLOCATABLE::dum(:,:)...END SUBROUTINEHaving an allocatable dummy argument means that there must be an explicit interface for any reference:i.e.if the procedure is not an internal or module procedure there must be an accessible interface block in any routine which references that procedure.Any actual argument that is passed to an allocatable dummy array must itself be an allocatable array;it must also have the same type,kind type parameters,and rank.For example:REAL,ALLOCATABLE::x(:,:)CALL s(x)The actual argument need not be allocated before calling the procedure,which may itself allocate or deallocate the argument.For example:PROGRAM example2REAL,ALLOCATABLE::x(:,:)OPEN(88,FILE=’myfile’,FORM=’unformatted’)CALL read_matrix(x,88)!...process x in some way!REWIND(88)CALL write_and_delete_matrix(x,88)END!MODULE moduleCONTAINS!!This procedure reads the size and contents of an array from an!unformatted unit.!SUBROUTINE read_matrix(variable,unit)REAL,ALLOCATABLE,INTENT(OUT)::variable(:,:)INTEGER,INTENT(IN)::unitINTEGER dim1,dim2READ(unit)dim1,dim2ALLOCATE(variable(dim1,dim2))READ(unit)variableCLOSE(unit)END SUBROUTINE!!This procedures writes the size and contents of an array to an!unformatted unit,and then deallocates the array.!SUBROUTINE write_and_delete_matrix(variable,unit)REAL,ALLOCATABLE,INTENT(INOUT)::variable(:,:)INTEGER,INTENT(IN)::unitWRITE(unit)SIZE(variable,1),SIZE(variable,2)WRITE(unit)variableDEALLOCATE(variable)END SUBROUTINEEND4.2Allocatable Function Results[4.x]The result of a function can be declared to be an allocatable array,e.g.FUNCTION af()RESULT(res)REAL,ALLOCATABLE::resOn invoking the function,the result variable will be unallocated.It must be allocated before returning from the function.For example:!!The result of this function is the original argument with adjacent!duplicate entries deleted(so if it was sorted,each element is unique).!FUNCTION compress(array)INTEGER,ALLOCATABLE::compress(:)INTEGER,INTENT(IN)::array(:)IF(SIZE(array,1)==0)THENALLOCATE(compress(0))ELSEN=1DO I=2,SIZE(array,1)IF(array(I)/=array(I-1))N=N+1END DOALLOCATE(compress(N))N=1compress(1)=array(1)DO I=2,SIZE(array,1)IF(array(I)/=compress(N))THENN=N+1compress(N)=array(I)END IFEND DOEND IFENDThe result of an allocatable array is automatically deallocated after it has been used.4.3Allocatable Structure Components[4.x]A structure component can be declared to be allocatable,e.g.MODULE matrix_exampleTYPE MATRIXREAL,ALLOCATABLE::value(:,:)END TYPEEND MODULEAn allocatable array component is initially not allocated,just like allocatable array variables.On exit from a procedure containing variables with allocatable components,all the allocatable components are automatically deallocated.This is in contradistinction to pointer components,which are not automatically deallocated.For example: SUBROUTINE sub(n,m)USE matrix_exampleTYPE(matrix)a,b,c!!a%value,b%value and c%value are all unallocated at this point.!ALLOCATE(a%value(n,m),b%value(n,m))!...do some computations,then!RETURN!!Returning from the procedure automatically deallocates a%value,b%value,!and c%value(if they are allocated).!ENDDeallocating a variable that has an allocatable array component deallocates the componentfirst;this happens recur-sively so that all ALLOCATABLE subobjects are deallocated with no memory leaks.Any allocated allocatable components of a function result are automatically deallocated after the result has been used. PROGRAM deallocation_exampleTYPE innerREAL,ALLOCATABLE::ival(:)END TYPETYPE outerTYPE(inner),ALLOCATABLE::ovalueEND TYPETYPE(outer)x!!At this point,x%ovalue is unallocated!ALLOCATE(x%ovalue(10))!!At this point,x%ovalue(i)%ival are unallocated,i=1,10!ALLOCATE(x%ovalue(2)%ival(1000),x%ovalue(5)%ival(9999))!!Only x%ovalue(2)%ival and x%ovalue(5)%ival are allocated!DEALLOCATE(x%ovalue)!!This has automatically deallocated x%ovalue(2)%ival and x%ovalue(5)%ival!ENDIn a structure constructor for such a type,the expression corresponding to an allocatable array component can be •the NULL()intrinsic,indicating an unallocated array,•an allocatable array which may be allocated or unallocated,or•any other array expression,indicating an allocated array.SUBROUTINE constructor_exampleUSE matrix_exampleTYPE(matrix)a,b,cREAL::array(10,10)=1REAL,ALLOCATABLE::alloc_array(:,:)a=matrix(NULL())!!At this point,a%value is unallocated!b=matrix(array*2)!!Now,b%value is a(10,10)array with each element equal to2.!c=matrix(alloc_array)!!Now,c%value is unallocated(because alloc_array was unallocated).!ENDIntrinsic assignment of such types does a“deep copy”of the allocatable array components;it is as if the allocatable array component were deallocated(if necessary),then if the component in the expression was allocated,the variable’s component is allocated to the right size and the value copied.SUBROUTINE assignment_exampleUSE matrix_exampleTYPE(matrix)a,b!!First we establish a value for a!ALLOCATE(a%value(10,20))a%value(3,:)=30!!And a value for b!ALLOCATE(b%value(1,1))b%value=0!!Now the assignment!b=a!!The old contents of b%value have been deallocated,and b%value now has!the same size and contents as a%value.!END4.4Allocatable Component ExampleThis example shows the definition and use of a simple module that provides polynomial arithmetic.To do this it makes use of intrinsic assignment for allocatable components,the automatically provided structure constructors and defines the addition(+)operator.A more complete version of this module would provide other operators such as multiplication.!!Module providing a single-precision polynomial arithmetic facility!MODULE real_poly_module!!Define the polynomial type with its constructor.!We will use the convention of storing the coefficients in the normal!order of highest degree first,thus in an N-degree polynomial,COEFF(1)!is the coefficient of X**N,COEFF(N)is the coefficient of X**1,and!COEFF(N+1)is the scalar.!TYPE,PUBLIC::real_polyREAL,ALLOCATABLE::coeff(:)END TYPE!PUBLIC OPERATOR(+)INTERFACE OPERATOR(+)MODULE PROCEDURE rp_add_rp,rp_add_r,r_add_rpEND INTERFACE!CONTAINSTYPE(real_poly)FUNCTION rp_add_r(poly,real)TYPE(real_poly),INTENT(IN)::polyREAL,INTENT(IN)::realINTEGER isizeIF(.NOT.ALLOCATED(poly%coeff))STOP’Undefined polynomial value in+’isize=SIZE(poly%coeff,1)rp_add_r%coeff(isize)=poly%coeff(isize)+realEND FUNCTIONTYPE(real_poly)FUNCTION r_add_rp(real,poly)TYPE(real_poly),INTENT(IN)::polyREAL,INTENT(IN)::realr_add_rp=rp_add_r(poly,real)END FUNCTIONTYPE(real_poly)FUNCTION rp_add_rp(poly1,poly2)TYPE(real_poly),INTENT(IN)::poly1,poly2INTEGER I,N,N1,N2IF(.NOT.ALLOCATED(poly1%coeff).OR..NOT.ALLOCATED(poly2%coeff))&STOP’Undefined polynomial value in+’!Set N1and N2to the degrees of the input polynomialsN1=SIZE(poly1%coeff)-1N2=SIZE(poly2%coeff)-1!The result polynomial is of degree NN=MAX(N1,N2)ALLOCATE(rp_add_rp%coeff(N+1))DO I=0,MIN(N1,N2)rp_add_rp%coeff(N-I+1)=poly1%coeff(N1-I+1)+poly2%coeff(N2-I+1) END DO!At most one of the next two DO loops is ever executedDO I=N1+1,Nrp_add_rp%coeff(N-I+1)=poly2%coeff(N2-I+1)END DODO I=N2+1,Nrp_add_rp%coeff(N-I+1)=poly1%coeff(N1-I+1)END DOEND FUNCTIONEND MODULE!!Sample program!PROGRAM exampleUSE real_poly_moduleTYPE(real_poly)p,q,rp=real_poly((/1.0,2.0,4.0/))!x**2+2x+4q=real_poly((/1.0,-5.5/))!x-5.5r=p+q!x**2+3x-1.5print1,’The coefficients of the answer are:’,r%coeff1format(1x,A,3F8.2)ENDWhen executed,the above program prints:The coefficients of the answer are: 1.00 3.00-1.504.5The MOVE ALLOC intrinsic subroutine[5.2]This subroutine moves an allocation from one allocatable variable to another.This can be used to expand an allocatable array with only one copy operation,and allows full control over where in the new array the values should go.For example:REAL,ALLOCATABLE::a(:),tmp(:)...ALLOCATE(a(n))...!Here we want to double the size of A,without losing any of the values!that are already stored in it.ALLOCATE(tmp(size(a)*2))tmp(1:size(a))=aCALL move_alloc(from=tmp,to=a)!TMP is now deallocated,and A has the new size and values.To have the values end up somewhere different,just change the assignment statement,for example to move them all to the end:tmp(size(a)+1:size(a)*2)=a4.6Allocatable scalars[5.2]The ALLOCATABLE attribute may now be applied to scalar variables and components,not just arrays.This is most useful in conjunction with polymorphism(CLASS)and/or deferred type parameters(e.g.CHARACTER(:));for more details see the“Typed allocation”,“Sourced allocation”and“Automatic reallocation”sections.4.7Automatic reallocation[5.2]If,in an assignment to a whole allocatable array,the expression being assigned is an array of a different size or shape, the allocatable array is reallocated to have the correct shape(in Fortran95this assignment would have been an error). For example:ALLOCATE(a(10))...a=(/(i,i=1,100)/)!A is now size100Similarly,if an allocatable variable has a deferred type parameter(these are described in a later section),and is either unallocated or has a value different from that of the expression,the allocatable variable is reallocated to have the same value for that type parameter.This allows for true varying-length character variables:CHARACTER(:),ALLOCATABLE::name...name=’John Smith’!LEN(name)is now10,whatever it was before.name=’?’!LEN(name)is now1.Note that since a subobject of an allocatable object is not itself allocatable,this automatic reallocation can be suppressed by using substrings(for characters)or array sections(for arrays),e.g.。
1 FORTRAN77四则运算符+ - * / ** (其中**表示乘方)在表达式中按优先级次序由低到高为: +或-→*或/→**→函数→()2 FORTRAN77变量类型2.1 隐含约定:I-N规则凡是以字母I,J,K,L,M,N六个字母开头的,即认为是整型变量,其它为实型变量。
2.2 用类型说明语句确定变量类型:可以改变I-N规则2.3 用IMPLICIT语句将某一字母开头的全部变量指定为所需类型如 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/-1.0,-1.0,-1.0/DATA A/-1.0/,B/-1.0/,C/-1.0/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字符位以后不能有内容。
ARGONNE NATIONAL LABORATORY9700South Cass AvenueArgonne,Illinois60439An Extended Set of FortranBasic Linear Algebra SubprogramsJack J.Dongarra,Jeremy Du Croz,Sven Hammarling,and Richard J.HansonMathematics and Computer Science DivisionTechnical Memorandum No.41(Revision3)September,1986ABSTRACTThis paper describes an extension to the set of Basic Linear Algebra Subprograms.The extensions are targeted at matrix-vector operations which should provide for efficient and portable implementations of algorithms for high performance computers.An Extended Set of FortranBasic Linear Algebra SubprogramsJack J.Dongarra†Mathematics and Computer Science DivisionArgonne National LaboratoryArgonne,Illinois60439Jeremy Du CrozNumerical Algorithms Group Ltd.NAG Central Office,Mayfield House256Banbury Road,Oxford OX27DESven HammarlingNumerical Algorithms Group Ltd.NAG Central Office,Mayfield House256Banbury Road,Oxford OX27DERichard J.HansonApplied Math2646Sandia National LaboratoryAlbuquerque,New Mexico87185Abstract—This paper describes an extension to the set of Basic Linear Algebra Subprograms.The exten-sions are targeted at matrix-vector operations which should provide for efficient and portable implementa-tions of algorithms for high performance computers.1.IntroductionIn1973Hanson,Krogh,and Lawson wrote an article in the SIGNUM Newsletter(Vol.8,no.4, page16)describing the advantages of adopting a set of basic routines for problems in linear algebra.The original basic linear algebra subprograms,now commonly referred to as the BLAS and fully described in Lawson,Hanson,Kincaid,and Krogh[9,10],have been very successful and have been used in a wide range of software including LINPACK[4]and many of the algorithms published by the ACM Transac-tions on Mathematical Software.In particular they are an aid to clarity,portability,modularity and maintenance of software and they have become a de facto standard for the elementary vector operations. An excellent discussion of the raison d’ˆe tre of the BLAS is given in Dodson and Lewis[1].Special versions of the BLAS,in some cases machine code versions,have been implemented on a number of computers,thus improving the efficiency of the BLAS.However,with some of the modern__________________†Work supported in part by the Applied Mathematical Sciences subprogram of the Office of EnergyResearch,U.S.Department of Energy,under Contract W-31-109-Eng-38.Typeset on October14,1992.machine architectures,the use of the BLAS is not the best way to improve the efficiency of higher level codes.On vector machines,for example,one needs to optimize at least at the level of matrix-vector operations in order to approach the potential efficiency of the machine(see[2and3]);and the use of the BLAS inhibits this optimization because they hide the matrix-vector nature of the operations from the compiler.During the Gatlinburg meeting of June,1984(Waterloo,Ontario)discussions among the partici-pants encouraged two of us(Dongarra and Hammarling)to prepare a proposed set of extended BLAS.At about the same time IFIP Working Group2.5started a project on the same subject at their annual meeting in Pasadena,CA.An initial proposal was drafted and presented at the Parvec IV workshop held at Purdue Univ.,Oct. 29-30,1984.At that time two more authors joined the project(Hanson and du Croz).A series of meet-ings were planned so that the project would reflect the best thinking of the mathematical software com-munity.Three meetings soliciting input were held.These occurred at SIAM conferences:The Spring Meeting of the Society,(Seatle,WA,July16-20,1984);The Conference on Applied Linear Algebra (Raleigh,NC,April29-May2,1985);The Fall Meeting of the Society,(Tempe,AZ,October28-30, 1985);The Conference on Parallel Processing for Scientific Computing(Norfolk,VA,November18-21, 1985).Earlier,a modified proposal was printed in the SIGNUM Newletter,[6].In that document we invited readers to send us their views and suggestions for changes to the design of the extended BLAS. Thus we have appealed to a wide audience within the mathematical software community.Our hope is that the proposed set of names that constitue the extended BLAS willfind wide application in the future software of numerical linear algebra and provide a useful tool for implementors and users.We believe that the time is right to specify an additional set of BLAS designed for matrix-vector operations.It has been our experience that a small set of matrix-vector operations occur frequently in the implementation of many of the most common algorithms in linear algebra.We define here the basic operations for that set,together with the naming conventions and the calling sequences.Routines at this level should provide a reasonable compromise between the sometimes conflicting aims of efficiency and modularity and it is our hope that efficient implementations will become available on a wide range of computer architectures.In this paper we shall refer to the existing BLAS of Lawson et al.as‘‘Level1BLAS’’,and the new extended set as‘‘Level2BLAS’’.The Level2BLAS involve O(mn)scalar operations where m and n are the dimensions of the matrix involved.These could be programmed by a series of calls to the Level1 BLAS,though we do not recommend that they be implemented in that way.Hence,in a natural sense,the Level2BLAS are performing basic operations at one level higher than the Level1BLAS.In[7]we present a model implementation of the Level2BLAS in Fortran77(extended to include a COMPLEX*16data type),and also a set of rigorous test programs.2.Scope of the Level2BLASThe following three types of basic operation are performed by the Level2BLAS:a)Matrix-vector products of the formy←αAx + βy, y←αA T x + βy,and y←αA T x + βywhereαandβare scalars,x and y are vectors and A is a matrix,andx← Tx, x← T T x,and x← T T x,where x is a vector and T is an upper or lower triangular matrix.b)Rank-one and rank-two updates of the formA←αxy T + A, A←αxy T + A, H←αxx T + H,and H←αxy T + α yx T + H, where H is a Hermitian matrix.c)Solution of triangular equations of the formx← T−1x, x← T−T x,and x← T −T x,where T is a non-singular upper or lower triangular matrix.Where appropriate,the operations are applied to general,general band,Hermitian,Hermitian band, triangular,and triangular band matrices in both real and complex arithmetic,and in single and double precision.In Appendix B we propose corresponding sets of routines in which the internal computation is per-formed in extended precision,and the vectors x and/or y are stored in extended precision,so that the extra internal precision is not all discarded on return from the routine.This proposal is aimed at machines with extended precision arithmetic registers;for example machines performing IEEE arithmetic[12].We propose these routines as an optional extension to the Level2BLAS because it is not possible to specify a complete set within the confines of ANSI Fortran77.The only case that can be realized is where the matrix is real single precision and the extended precision vectors are real double precision.Code for these routines is not included in[7].3.Naming ConventionsThe name of a Level2BLAS is in the LINPACK style and consists offive characters,the last of which may be blank.The fourth andfifth characters in the name denote the type of operation,as follows:MV-Matrix-vector productR-Rank-one updateR2-Rank-two updateSV-Solve a system of linear equationsCharacters two and three in the name denote the kind of matrix involved,as follows:GE General matrixGB General band matrixHE Hermitian matrixSY Symmetric matrixHP Hermitian matrix stored in packed formSP Symmetric matrix stored in packed formHB Hermitian band matrixSB Symmetric band matrixTR Triangular matrixTP Triangular matrix in packed formTB Triangular band matrixThefirst character in the name denotes the Fortran data type of the matrix,as follows:S REALD DOUBLE PRECISIONC COMPLEXZ COMPLEX*16or DOUBLE COMPLEX(if available)The available combinations are indicated in Table3.1below.In thefirst column,under complex,the ini-tial C may be replaced by Z.In the second column,under real,the initial S may be replaced by D.See Appendix C for the full subroutine calling sequences.The collection of routines can be thought of as being divided into four separate parts,real,double precision,complex,and complex*16.The routines can be written in ANSI standard Fortran77,with the exception of the routines that use COMPLEX*16variables.These routines are included for complete-ness and for their usefulness on those systems which support this data type;but because they do not con-form to the Fortran standard,they may not be available on all machines.Table3.1complex real MV R R2SVCGE SGE**CGB SGB*CHE SSY***CHP SSP***CHB SSB*CTR STR**CTP STP**CTB STB**For the general rank-1update(GER)we specify two complex routines:CGERC for A←αxy T + A and CGERU for A←αxy T + A.This is the only exception to the one to one correspondence between real and complex routines.See section7for further discussion.We do not specify routines for rank-one and rank-two updates applied to band matrices because these can be obtained by calls to the rank-one and rank-two full matrix routines.This is illustrated in Appendix A.4.Argument ConventionsWe follow a similar convention for the argument lists to that for the Level1BLAS,but with exten-sions where comparable arguments are not present in the Level1BLAS.The order of arguments is as fol-lows:a)Arguments specifying options.b)Arguments defining the size of the matrix.c)Input scalar.d)Description of the input matrix.e)Description of input vector(s).f)Input scalar(associated with input-output vector).g)Description of the input-output vector.h)Description of the input-output matrix.Note that not each category is present in each of the routines.The arguments that specify options are character arguments with the names TRANS,UPLO,and DIAG.TRANS is used by the matrix-vector product routines as follows:Value Meaning_________________________________________________‘N’Operate with the matrix.‘T’Operate with the transpose of the matrix.‘C’Operate with the conjugate transpose of the matrix.In the real case the values‘T’and‘C’have the same meaning.UPLO is used by the Hermitian,symmetric,and triangular matrix routines to specify whether the upper or lower triangle is being referenced as follows:Value Meaning____________________‘U’Upper triangle‘L’Lower triangleDIAG is used by the triangular matrix routines to specify whether or not the matrix is unit triangu-lar,as follows:Value Meaning_______________________‘U’Unit triangular‘N’Non-unit triangularWhen DIAG is supplied as‘U’the diagonal elements are not referenced.We recommend that the equivalent lower case characters be accepted with the same meaning, although,because they are not included in the standard Fortran character set,their use may not be sup-ported on all systems.See Section7for further discussion.It is worth noting that actual character arguments in Fortran may be longer than the corresponding dummy arguments.So that,for example,the value‘T’for TRANS may be passed as‘TRANSPOSE’.The size of the matrix is determined by the arguments M and N for an m by n rectangular matrix; and by the argument N for an n by n symmetric,Hermitian,or triangular matrix.Note that it is permissi-ble to call the routines with M or N=0,in which case the routines exit immediately without referencing their vector or matrix arguments.The bandwidth is determined by the arguments KL and KU for a rec-tangular matrix with kl sub-diagonals and ku super-diagonals;and by the argument K for a symmetric, Hermitian,or triangular matrix with k sub-diagonals and/or super-diagonals.The description of the matrix consists either of the array name(A)followed by the leading dimen-sion of the array as declared in the calling(sub)program(LDA),when the matrix is being stored in a two-dimensional array;or the array name(AP)alone when the matrix is being stored as a(packed)vec-tor.In the former case the actual array must contain at least((n−1)d + l)elements,where d is the lead-ing dimension of the array,d≥ l,and l = m for the GE routines,l = n for the SY,HE and TR routines, l = kl + ku + 1for the GB routines,and l = k+1for the SB,HB or TB routines.For packed storage the actual array must contain at least n(n+1)/2elements.The scalars always have the dummy argument names ALPHA and BETA.As with the existing BLAS the description of a vector consists of the name of the array(X or Y)fol-lowed by the storage spacing(increment)in the array of the vector elements(INCX or INCY).The incre-ment is allowed to be positive or negative-but not zero(see section7).When the vector x consists of k elements,then the corresponding actual array argument X must be of length at least(1+(k-1)|INCX|). For those routines that include the argument BETA,when BETA is supplied as zero then the array Y need not be set on input,so that operations such as y←αAx may be performed without initially setting y to zero.The following values of arguments are invalid:Any value of the character arguments DIAG,TRANS,or UPLOwhose meaning is not specified.M<0N<0KL<0KU<0K<0LDA<MLDA<KL+KU+1LDA<N for the HE,SY,and TR routines.LDA<K+1for the HB,SB,and TB routines.INCX=0INCY=0If a routine is called with an invalid value for any of its arguments,then it must report the fact and ter-minate execution of the program.In the model implementation(see[7]),each routine,on detecting an error,calls a common error handling routine XERBLA,passing to it the name of the routine and the number of thefirst argument which is in error.Specialized implementations may call system-specific exception-handling and diagnostic facilities,either via an auxiliary routine XERBLA or directly from the routines.One advantage of using XERBLA is that the test program can then test that all errors are detected(see[7]).5.Storage ConventionsUnless otherwise stated it is assumed that matrices are stored conventionally in a2-dimensionalstored in array-element A(I,J).array with matrix-element aijThe routines for real symmetric and complex Hermitian matrices allow for the matrix to be stored in either the upper(UPLO=‘U’)or lower triangle(UPLO=‘L’)of a two dimensional array,or to be packed in a one dimensional array.In the latter case the upper triangle may be packed sequentiallycolumn by column(UPLO=‘U’),or the lower triangle may be packed sequentially column by column (UPLO=‘L’).Note that for real symmetric matrices packing the upper triangle by column is equivalent to packing the lower triangle by rows,and packing the lower triangle by columns is equivalent to packing the upper triangle by rows.(For complex Hermitian matrices the only difference is that the off-diagonal elements are conjugated.)For triangular matrices the argument UPLO serves to define whether the matrix is upper(UPLO=‘U’)or lower(UPLO=‘L’)triangular.In packed storage the triangle has to be packed by column.The band matrix routines allow storage in the same style as with LINPACK,so that the j th column of the matrix is stored in the j th column of the Fortran array.For a general band matrix the diagonal of the matrix is stored in the ku+1th row of the array.For a Hermitian or symmetric matrix either the upper triangle(UPLO=‘U’)may be stored in which case the leading diagonal is in the k+1th row of the array, or the lower triangle(UPLO=‘L’)may be stored in which case the leading diagonal is in thefirst row of the array.For an upper triangular band matrix(UPLO=‘U’)the leading diagonal is in the k+1th row of the array and for a lower triangular band matrix(UPLO=‘L’)the leading diagonal is in thefirst row.For a Hermitian matrix the imaginary parts of the diagonal elements are of course zero and thus the imaginary parts of the corresponding Fortran array elements need not be set,but are assumed to be zero. In the R and R2routines these imaginary parts will be set to zero on return,except whenα = 0,in which case the routines exit immediately.For packed triangular matrices the same storage layout is used whether or not DIAG=‘U’,i.e. space is left for the diagonal elements even if those array elements are not referenced.6.Specification of the Level2BLASType and dimension for variables occurring in the subroutine specifications are as follows:INTEGER INCX,INCY,K,KL,KU,LDA,M,NCHARACTER*1DIAG,TRANS,UPLOFor routines whosefirst letter is an S:REAL ALPHA,BETAREAL X(*),Y(*)REAL A(LDA,*)REAL AP(*)For routines whosefirst letter is a DDOUBLE PRECISION ALPHA,BETADOUBLE PRECISION X(*),Y(*)DOUBLE PRECISION A(LDA,*)DOUBLE PRECISION AP(*)For routines whosefirst letter is a C:COMPLEX ALPHACOMPLEX BETACOMPLEX X(*),Y(*)COMPLEX A(LDA,*)COMPLEX AP(*)except that for CHER and CHPR the scalarαis real so that thefirst declaration above is replaced by:REAL ALPHAFor routines whosefirst letter is Z:COMPLEX*16ALPHA DOUBLE COMPLEX ALPHACOMPLEX*16BETA DOUBLE COMPLEX BETACOMPLEX*16X(*),Y(*)or DOUBLE COMPLEX X(*),Y(*)COMPLEX*16A(LDA,*)DOUBLE COMPLEX A(LDA,*)COMPLEX*16AP(*)DOUBLE COMPLEX AP(*)except that for ZHER and ZHPR thefirst declaration above is replaced by:DOUBLE PRECISION ALPHAThe generic names,argument lists and specifications for the extended BLAS now follow.Refer to table 3.1for the specific subroutine names.a)General Matrix Vector Productsfor a general matrix:_GEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)for a general band matrix:_GBMV(TRANS,M,N,KL,KU,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)Operation:if TRANS = ‘N’, y←αAx + βyif TRANS = ‘T’, y←αA T x + βyif TRANS = ‘C’, y←αA T x + βy.b)Symmetric or Hermitian Matrix Vector Productsfor a symmetric or Hermitian matrix:_SYMV(UPLO,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)_HEMV(UPLO,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)for a symmetric or Hermitian matrix in packed storage:_SPMV(UPLO,N,ALPHA,AP,X,INCX,BETA,Y,INCY)_HPMV(UPLO,N,ALPHA,AP,X,INCX,BETA,Y,INCY)for a symmetric or Hermitian band matrix:_SBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) _HBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)Operation:y←αAx + βy .c)Triangular Matrix Vector Productsfor a triangular matrix:_TRMV(UPLO,TRANS,DIAG,N,A,LDA,X,INCX)for a triangular matrix in packed storage:_TPMV(UPLO,TRANS,DIAG,N,AP,X,INCX)for a triangular band matrix:_TBMV(UPLO,TRANS,DIAG,N,K,A,LDA,X,INCX) Operation:if TRANS = ‘N’, x← Txif TRANS = ‘T’, x← T T xif TRANS = ‘C’, x← T T xd)Triangular equation solversfor a triangular matrix:_TRSV(UPLO,TRANS,DIAG,N,A,LDA,X,INCX)for a triangular matrix in packed storage:_TPSV(UPLO,TRANS,DIAG,N,AP,X,INCX)for a triangular band matrix:_TBSV(UPLO,TRANS,DIAG,N,K,A,LDA,X,INCX) Operation:if TRANS = ‘N’, x← T−1xif TRANS = ‘T’, x← T−T xif TRANS = ‘C’, x← T −T x.e)General Rank-1Updates:for a general matrix:_GER_(M,N,ALPHA,X,INCX,Y,INCY,A,LDA)for real matrices:SGER or DGER performs the operation A←αxy T + A.for complex matrices:CGERC or ZGERC performs the operation A←αxy T + A andCGERU or ZGERU performs the operation A←αxy T + A.f)Symmetric or Hermitian Rank-1Updates:for a symmetric or Hermitian matrix:_SYR(UPLO,N,ALPHA,X,INCX,A,LDA)_HER(UPLO,N,ALPHA,X,INCX,A,LDA)for symmetric or Hermitian matrix in packed storage:_SPR(UPLO,N,ALPHA,X,INCX,AP)_HPR(UPLO,N,ALPHA,X,INCX,AP)Operation:A←αxx T + Afor real symmetric matrices this is simplyA←αxx T + A .g)Symmetric or Hermitian Rank-2Updates:for a symmetric or Hermitian matrix:_SYR2(UPLO,N,ALPHA,X,INCX,Y,INCY,A,LDA)_HER2(UPLO,N,ALPHA,X,INCX,Y,INCY,A,LDA)for symmetric or Hermitian matrix in packed storage:_SPR2(UPLO,N,ALPHA,X,INCX,Y,INCY,AP)_HPR2(UPLO,N,ALPHA,X,INCX,Y,INCY,AP)Operation:A←αxy T + α yx T + Afor real symmetric matrices this is simplyA←αxy T + αyx T + A .7.RationaleThe three basic matrix-vector operations chosen(Section2)were obvious candidates because they occur in a wide range of linear algebra applications,and they occur at the innermost level of many algo-rithms.The hard decision was to restrict the scope only to these operations,since there are many other potential candidates,such as matrix scaling and sequences of plane rotations.Similarly,we could have extended the scope by applying the operations to other types of matrices such as complex symmetric or augmented band matrices.We have aimed at a reasonable compromise between a much larger number of routines each performing one type of operation(e.g.x← L−T x),and a smaller number of routines with a more complicated set of options.There are in fact,in each precision,16real routines performing alto-gether43different operations,and17complex routines performing58different operations.We feel that to extend the scope further would significantly reduce the chances of having the rou-tines implemented efficiently over a wide range of machines,because it would place too heavy a burden on implementors.On the other hand,to restrict the scope further would place too narrow a limit on the potential applications of the level2BLAS.We have adhered to the conventions of the level 1BLAS in allowing an increment argument to be associated with each vector,so that a vector could,for example,be a row of a matrix.This increment may be negative,in which case the elements of the vectors are taken in reverse order.This affects the definition of the operation.For example,if m = n = 3and INCX and INCY are both negative,the _GEMV routines with TRANS=’N’perform the operation:y 1y 2y 3 ← α a 31a 21a 11 a 32a 22a 12 a 33a 23a 13x 1x 2x 3 + β y 1y 2y 3 .However,in contrast to the level 1BLAS we do not allow INCX or INCY to be zero.This feature wouldhave little usefulness,would complicate implementation of the routines on many vector machines,and,when the associated vector is an output vector,its meaning is ambiguous.As noted earlier,corresponding to the real routine SGER we specify two complex routines CGERC(for A ← αxyT + A )and CGERU (for A ← αxy T+ A ).Both are frequently required.An alternative would be to provide a single complex routine CGER with an option argument;however this argument would have become redundant in the real routine SGER.Rather than have redundant arguments,or different argument lists for the real and complex routines,we have chosen two distinct complex routines;they are analogous to the level 1BLAS CDOTC (c ← c + x T y )and CDOTU (c ← c + x Ty ).Note that no check has been included for singularity,and near singularity,in the triangular equation solving routines.The requirements for such a test depend upon the application and so we felt that this should not be included,but should instead be performed before calling the triangular solver.On certain machines,which do not use the ASCII sequence on all of their Fortran systems,lower case characters may not exist,so that the innocent looking argument ‘t’,passed through the argument TRANS for designating a transposed matrix,is not in the Fortran character set.Some UNIVAC systems do not have a lower case representation using the ‘field data’character set.On the CDC NOS-2system,a mechanism is provided for a full 128ASCII character set by using pairs of 6-bit host characters for cer-tain 7-bit ASCII characters.This means that there is a ‘2for 1’physical extension of the logical records that contain lower case letters.This fact can hamper portability of codes written on ASCII machines that are later moved to CDC systems.The only safe way to proceed is to convert the transported text entirely into the Fortran character set.On the other hand we believe that users on ASCII character set systems may wish to treat upper and lower case letters as equivalent in meaning.If this is done,it means that text that will be transported to machines of unknown types must have the ASCII set mapped into the Fortran character set before the text is moved.The band storage scheme used by the GB,HB,SB,and TB routines has columns of the matrix stored in columns of the array,and diagonals of the matrix stored in rows of the array.This is the storage scheme used by LINPACK.An alternative scheme (used in some EISPACK [8,11]routines)has rows of the matrix stored in rows of the array,and diagonals of the matrix stored in columns of the array.The latter scheme has the advantage that a band matrix-vector product of the form y ← αAx + βy can becomputed using long vectors(the diagonals of the matrix)stored in contiguous elements,and hence is much more efficient on some machines(e.g.CDC Cyber205)than thefirst scheme.However other com-putations involving band matrices,such as x← Tx,x← T−1x and LU and U T U factorization,cannot be organized‘by diagonals’;instead the computation sweeps along the band,and the LINPACK storage scheme has the advantage of reducing the number of page swaps and allowing contiguous vectors(the columns of the matrix)to be used.We considered the possibility of generalizing the rank-1and rank-2updates to rank-k updates. Rank-k updates with k > 1(but k << n)can achieve significantly better performance on some machines than rank-1[5].But to take advantage of this usually requires complicating the calling algorithm;and moreover rank-k updates with k∼∼ n would allow an even higher level operation such as matrix multipli-cation‘in by the back door’.We prefer to keep to a clean concept of genuine matrix-vector operations.8.AcknowledgementsA draft proposal that led to this specification was discussed at the Parvec IV Workshop organized by John Rice at Purdue University on October29-30,1984and at various SIAM conferences.We wish to thank all the participants at the workshop and meetings for their comments,discussions,and encourage-ment,as well as the many people who have sent us comments separately.13.References[1] D.S.Dodson and J.G.Lewis,"Issues relating to extension of the Basic Linear Algebra Subpro-grams",ACM SIGNUM Newsletter,vol20,no1,(1985),2-18.[2]J.J.Dongarra and S.C.Eisenstat,‘‘Squeezing the Most out of an Algorithm in CRAY Fortran,’’ACM Transactions on Mathematical Software,Vol.10,No.3,(1984),221-230.[3]J.J.Dongarra,Increasing the Performance of Mathematical Software through High-Level Modular-ity.Proceedings of the Sixth International Symposium on Computing Methods in Engineering and Applied Sciences.(Versailles,France).North-Holland(1984),pp239-248.[4]J.J.Dongarra,J.R.Bunch,C.B.Moler,and G.W.Stewart,LINPACK Users’Guide,SIAM Publica-tions,Philadelphia,1979.[5]J.J.Dongarra,L.Kaufman,and S.Hammarling,Squeezing the Most out of Eigenvalue Solvers onHigh-Performance Computers,Linear Algebra and Its Applications,77,pp113-136,(1986).[6]J.J.Dongarra,J.J.Du Croz,S.Hammarling,R.J.Hanson,A Proposal for an Extended Set of FortranBasic Linear Algebra Subprograms,ACM SIGNUM Newsletter,vol.20,no.1,1985.[7]J.J.Dongarra,J.J.Du Croz,S.Hammarling,R.J.Hanson,Model Implementation and Test Packagefor the Extended BLAS,Argonne National Laboratory Report,ANL MCS-TM81,August1986.[8] B.S.Garbow,J.M.Boyle,J.J.Dongarra,C.B.Moler,Matrix Eigensystem Routines-EISPACKGuide Extension,Lecture Notes in Computer Science,Vol.51,Springer-Verlag,Berlin,1977.[9] wson,R.Hanson,D.Kincaid,and F.Krogh,‘‘Basic Linear Algebra Subprograms for FortranUsage,’’ACM Transactions on Mathematical Software5(1979),308-323.[10] wson,R.Hanson,D.Kincaid,and F.Krogh,‘‘Algorithm539:Basic Linear Algebra Subpro-grams for Fortran Usage,’’ACM Transactions on Mathematical Software5(1979),324-325.[11] B.T.Smith,J.M.Boyle,J.J.Dongarra,B.S.Garbow,Y.Ikebe,V.C.Klema,and C.B.Moler,MatrixEigensystem Routines-EISPACK Guide,Lecture Notes in Computer Science,Vol.6,2nd edition, Springer-Verlag,Berlin,1976.[12]IEEE Standard for Binary Floating-Point Arithmetic,ANSI/IEEE Std754-1985,The IEEE Inc.,New York,(1985).。