Giter Site home page Giter Site logo

beliavsky / fortrantip Goto Github PK

View Code? Open in Web Editor NEW
60.0 4.0 13.0 768 KB

Short instructional Fortran codes associated with Twitter @FortranTip

Home Page: https://zmoon.github.io/FortranTipBrowser/

License: The Unlicense

Fortran 97.43% C 1.72% C++ 0.84%
fortran tips fortran-tutorial twitter tutorial tutorials modern-fortran educational snippets learn learning

fortrantip's Introduction

FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip . Search tips and run codes at FortranTipBrowser.

Index of Tweets, Most Recent First, with Associated Code. A List by Topic is here.

Namelists blog post by Antoine Dauptain 7:11 AM · Mar 3, 2024
Installing gfortran on Windows 6:44 AM · Mar 2, 2024
Overloading of asterisk (*) -- post by John Harper 8:57 AM · Mar 1, 2024
Special meaning of asterisk (*) in DATA, READ, and NAMELIST 3:24 AM · Feb 29, 2024
Variables set in a DATA statement have the SAVE attribute 6:44 AM · Feb 28, 2024
DATA statement should be placed just after declarations 10:00 PM · Feb 26, 2024
New preprint "Accelerating Fortran Codes: A Method for Integrating Coarray Fortran with Cuda Fortran and Openmp" 4:57 PM · Feb 25, 2024
CHARACTER (len=*) and * in declarations of named constant arrays 5:58 PM · Feb 23, 2024
Use unformatted stream I/O to quickly and exactly store data. 7:02 AM · Jan 12, 2024 unformatted_stream.f90
Declare and set quadruple precision variables in a standard-conforming way by setting a KIND 6:52 AM · Dec 25, 2023 quad.f90
Fortran 2023 Standard and Interpretation Document 8:32 AM · Dec 24, 2023
Access comp.lang.fortran and other Usenet groups with Nemoweb 11:40 AM · Dec 23, 2023
Fortls is a language server for Fortran that interfaces with a code editor 8:11 AM · Dec 22, 2023
Link to talk on Using the HPE Cray Programming Environment to Port and Optimize (Fortran) Applications to a GPU environment 6:53 AM · Dec 20, 2023
Physical constants are available from the NIST codata project 7:24 AM · Dec 19, 2023
Fast_math is a library of functions for summation, trig, log, and sqrt that is faster and more accurate than the compiler intrinsics on some platforms. 8:14 AM · Dec 18, 2023
Feq-parse allows you to define functions as character strings and evaluate them on-the-fly. 7:51 AM · Dec 17, 2023
Fortran-shlex ports the Python’s shlex shell-like lexer. 6:17 AM · Dec 16, 2023
Brad Richardson's videos on Fortran 2023 and other topics 9:10 AM · Dec 15, 2023
Fortran is ranked 12th in the December Tiobe programming language index 6:50 AM · Dec 12, 2023
Test-drive from @fortranlang and other unit testing frameworks 6:17 AM · Dec 11, 2023
Fortran testing "unframework" 6:14 AM · Dec 11, 2023
Ifx is now the flagship Intel Fortran compiler, replacing ifort. 6:39 AM · Dec 10, 2023
PlusFORT 8, a suite of tools for analyzing and improving Fortran programs, is free for noncommercial use 6:47 AM · Dec 9, 2023
Modern Fortran Explained: Incorporating Fortran 2023 published 11:11 AM · Dec 8, 2023
Use the optional KIND argument of SIZE, MINLOC, FINDLOC etc. for large arrays. 10:21 AM · Jun 7, 2022 size_test.f90
With sequence association, the shapes of the actual and dummy arguments need not match. 12:42 PM · Jun 1, 2022 print_mat.f90
Sequence association effectively lets you pass a pointer to an array element. 8:58 AM · May 31, 2022
Wrap a procedure with explicit shape array arguments in a procedure with an assumed shape arguments for safety. 8:56 AM · May 31, 2022 wrap_explicit_shape.f90
Special meanings of * and / in list-directed input 8:50 AM · May 26, 2022 list_directed_read.f90
Ways of declaring character variables 6:43 AM · May 25, 2022
List of books with Fortran code other than Fortran textbooks. 6:47 AM · May 22, 2022
C can call Fortran procedures with prototypes generated by gfortran -fc-prototypes. 7:58 AM · May 21, 2022 call_print_stats.c print_stats.f90
An omitted Fortran optional argument corresponds to a NULL argument of a C function. 8:47 AM · May 20, 2022 xstrtof.f90
Use c_funloc() to pass a Fortran function as an argument to a C function. 7:29 AM · May 19, 2022 c_func_ptr.f90 cfuncptr.c
Use valgrind to find memory leaks in programs that use pointers. 7:09 AM · May 18, 2022 leak.f90
Use TYPE(C_PTR) and C_F_POINTER to call a C function returning a pointer. 10:49 AM · May 17, 2022 c_f_pointer.f90 squares.c
An allocated allocatable array can be passed to C as an explicit-shape array. 8:33 AM · May 16, 2022 xscale.f90 scale_vec.c
Common block and module variables with bind(c) can be accessed from C. 8:35 AM · May 15, 2022 xcircle.f90 circle.c
Fortran array x(n1,n2) passed to C array x[n2][n1] 9:50 AM · May 14, 2022 xcol_sum.f90 sum_rows.c
Use the std::span container from C++ 20 to view a contiguous Fortran array with a STL-compatible interface. 8:36 AM · May 12, 2022 test_sort.f90 sort.cpp
C++ functions can be called from Fortran if they are declared extern "C" and have C-like arguments. 9:09 AM · May 8, 2022 xnormal.f90 normal_array.cpp
The Fortran name can differ from the C name of a function if the NAME attribute appears in BIND. 7:53 AM · May 7, 2022 printf.f90
A simple derived type with the BIND(C) attribute interoperates with a C struct. 8:26 AM · May 6, 2022
Non-pointer arguments of C functions should have the VALUE attribute in the Fortran interface. 9:36 AM · May 5, 2022 xsum_vec.f90 sum_vec.c
C library functions can be called if an INTERFACE is provided. 2:35 PM · May 4, 2022 atoi_vs_read.f90
Fortran 2003 standardized the interoperation of Fortran and C. 9:06 AM · May 3, 2022
Use compiler options to catch the use of uninitialized variables. 8:15 AM · May 2, 2022
B, O, Z edit descriptors can be used to print integers as binary, octal, or hexadecimal. 8:44 AM · May 1, 2022 boz.f90
Use IANY instead of nested IOR, IALL instead of nested IAND. 11:21 PM · Apr 29, 2022 iany.f90
When is the -ffast-math option safe? 7:14 AM · Apr 29, 2022
Use ifort -fast or gfortran -O3 -march=native for speed. 7:09 AM · Apr 28, 2022
Compilers may accept extensions by default but have options to flag non-standard code. 8:00 AM · Apr 26, 2022
Compiler Explorer shows the assembly code generated by many Fortran compilers. 7:28 AM · Apr 25, 2022
Fortran-lang has a section on Building Programs, and F18 has a compiler options comparison. 9:28 AM · Apr 23, 2022
Fortran Package Manger simplifies building programs. 7:18 AM · Apr 22, 2022
Compilation can fail if there is no main program or if a USEd module has not been compiled. 7:42 AM · Apr 21, 2022
Create an executable in one step by compiling all source files or by compiling source files with -c and linking the object files. 7:40 AM · Apr 21, 2022
NOT, IAND, IOR, and IEOR perform logical operations on the bit representations of integers. 8:05 AM · Apr 20, 2022 bit_func.f90
TRANSFER can be used to store one type in another type. 8:12 AM · Apr 19, 2022 transfer.f90
Use PACK to select records from an array of derived types. 8:01 AM · Apr 18, 2022 query.f90
Fortran codes are listed by topic at the fortran-lang package index and Fortran Code on GitHub 7:41 AM · Apr 17, 2022
Implied do loop can access arbitrary derived type array sections. 8:10 AM · Apr 16, 2022 derived_type_implied_do.f90
Derived type array sections are allowed before or after the % component selector, but not in both places. 8:12 AM · Apr 15, 2022 derived_type_section.f90
Serialize a derived type using unformatted stream I/O. 8:51 AM · Apr 14, 2022 dt_stream.f90
PDT can have fixed parameters at compile time or be ALLOCATABLE. 8:34 AM · Apr 13, 2022
PDT can have array dimension, KIND, and character LEN parameters. 8:33 AM · Apr 13, 2022 pdt_matrix.f90
Links to tutorials on parameterized derived types (PDT). 8:55 AM · Apr 12, 2022
Deallocating a derived type deallocates its allocatable components. 8:57 AM · Apr 11, 2022 alloc_dt.f90
MOVE_ALLOC may be faster than RESHAPE or allocation on asignment to resize an array. 8:04 AM · Apr 10, 2022 move_alloc_bench.f90
Use MOVE_ALLOC to resize an array. 7:08 AM · Apr 10, 2022 move_alloc.f90
If unsure, test whether a variable is ALLOCATED before using DEALLOCATE. 7:41 AM · Apr 9, 2022
ALLOCATE has an optional ERRMSG specifier. 7:40 AM · Apr 8, 2022 alloc_errmsg.f90
ASSOCIATE to an array-valued expression allocates an array. 6:51 AM · Apr 7, 2022
ALLOCATE with SOURCE or MOLD to set values or SHAPE. 6:44 AM · Apr 7, 2022 alloc_source_mold.f90
Place IMPLICIT NONE before CONTAINS in a module. 8:32 AM · Apr 6, 2022
Scratch files are unnamed temporary files for I/O. 8:22 AM · Apr 5, 2022 scratch.f90
Read a file into a string with unformatted stream. 7:20 AM · Apr 4, 2022 file_to_string.f90
Because recursive I/O is prohibited, a function should use ERROR STOP msg instead of PRINT statements for error messages. 7:49 AM · Apr 3, 2022 recursive_io.f90
Use an implied do loop with a dummy variable to skip fields when reading a file. 7:09 AM · Apr 2, 2022 skip_columns.f90
List-directed READ will use several lines if necessary. 7:40 AM · Apr 1, 2022 list_directed.f90
MOOC on "Defensive programming and debugging" 11:46 AM · Mar 31, 2022
Use the "(a)" format to read a line of a file into a string. 7:31 AM · Mar 31, 2022 read_line.f90
Error in READ statement causes all variables to become undefined. 8:22 AM · Mar 30, 2022 read_err.f90
Use an implied do loop with TRIM to print an array of character variables without trailing blanks. 7:36 AM · Mar 29, 2022 trim_loop.f90
print*,char(7) causes the program to beep. 7:12 AM · Mar 28, 2022
DO WHILE loop iterates as long as condition at beginning is met. 7:18 AM · Mar 27, 2022 do_while.f90
Invalid loop bounds were discussed at Fortran Discourse. 7:00 AM · Mar 26, 2022
Beware of a loop to huge(i), since huge(i)+1 is out of range. 6:44 AM · Mar 26, 2022 huge_loop.f90
Number of iterations in a loop is determined at the beginning. 7:47 AM · Mar 25, 2022 loop_bound.f90
Changing a loop index within a loop is invalid. 8:48 AM · Mar 24, 2022 loop_index.f90
CYCLE skips the remaining statements in a loop. 8:06 AM · Mar 23, 2022 cycle.f90
EXIT can be used to leave a named outer loop. 7:44 AM · Mar 22, 2022 loop_label.f90
Use REWIND and BACKSPACE to change file position. 8:02 AM · Mar 21, 2022 rewind.f90
Slash / terminates a record. 10:43 AM · Mar 20, 2022 slash.f90
Stream input/output article by Clive Page 8:03 AM · Mar 19, 2022
Specific array elements can read or written to unformatted stream file by specifying the POS. 7:53 AM · Mar 19, 2022 stream_pos_dt.f90
DIRECT access file allows access to arbitrary record without looping over the previous records. 8:14 AM · Mar 18, 2022 direct_access.f90
How to append to a file or delete it 7:41 AM · Mar 17, 2022 write_append.f90
Use INQUIRE to get unit and file properties. 8:09 AM · Mar 16, 2022 inquire.f90
Use NEWUNIT in OPEN to get an unused unit number. 7:51 AM · Mar 15, 2022 newunit.f90
Number of files open simultaneously is limited, so they should be closed when possible. 7:58 AM · Mar 14, 2022 open_units_limit.f90
Write to many files by creating file names with internal write. 10:28 AM · Mar 13, 2022 write_many_files.f90
Unit n is connected to fort.n by default for most compilers. 7:40 AM · Mar 12, 2022 implicitly_connected.f90
Connect INPUT_UNIT and OUTPUT_UNIT to files to redirect standard input and output. 8:39 AM · Mar 11, 2022 output_unit.f90
Use ALLOCATABLE arrays or ASSOCIATE instead of POINTER when possible. 7:33 AM · Mar 10, 2022
Pointer should be initialized to null() to avoid undefined association status. 8:16 AM · Mar 9, 2022 pointer_use.f90
Pointer can remap array shape and bounds. 7:14 AM · Mar 8, 2022 pointer_reshape.f90
Bounds of associate-name for whole array or array section selector 7:38 AM · Mar 7, 2022 associate_bounds.f90
Tips by topic 9:03 AM · Mar 6, 2022
A variable ASSOCIATEd to an ALLOCATABLE variable is not ALLOCATABLE. 7:30 AM · Mar 6, 2022 associate_alloc.f90
ASSOCIATE statement can set several independent variables. 7:33 AM · Mar 5, 2022 associate_many.f90
ASSOCIATE is preferred over POINTER to create an alias because POINTER can inhibit optimization. 7:16 AM · Mar 4, 2022 associate_vs_pointer.f90
Pointer assignment and ASSOCIATE can create shallow copies. 7:59 AM · Mar 3, 2022 copy.f90
Internal procedures have access to variables from the host unless they are overridden by local variables. 8:29 AM · Mar 2, 2022 scope.f90
BLOCK construct allows declarations after executable statements. 8:08 AM · Mar 1, 2022 block.f90
Five free C C++ Fortran compiler families 8:38 AM · Feb 28, 2022
Errors in a procedure can be handled with an optional argument. 6:53 AM · Feb 27, 2022 optional_err.f90
Check that assumed-shape array arguments have consistent dimensions. 8:21 AM · Feb 26, 2022 error_handling.f90
ERROR STOP vs. STOP. 7:07 AM · Feb 25, 2022 error_stop.f90
Assumed type arguments have no declared type. 7:34 AM · Feb 24, 2022 assumed_type.f90
Unlimited polymorphic pointer can point to any type. 8:03 AM · Feb 23, 2022 unlimited_pointer.f90
Unlimited polymorphic allocatable variable can be set to any type. 7:36 AM · Feb 23, 2022 unlimited_poly.f90
Fortran 2018 procedures can have assumed-rank arguments. 7:59 AM · Feb 22, 2022 assumed_rank.f90
storage_size(A) returns the storage size of argument A in bits. 7:33 AM · Feb 21, 2022 storage_size.f90
A derived type can have PRIVATE components. 7:21 AM · Feb 20, 2022 dt_private.f90
A derived type component can have a default value. 6:44 AM · Feb 19, 2022 type_constructor_optional.f90
A derived type can have derived type components. 7:32 AM · Feb 18, 2022 derived_type_composition.f90
A derived type can be used where a scalar is needed. 7:59 AM · Feb 17, 2022 elemental_func_arg.f90
Modern Fortran Reference Card and Quick Reference/Cheat Sheet. 7:09 AM · Feb 16, 2022
Bounds of an allocatable array are preserved when passed to an allocatable, intent(in) or intent(in out) argument. 7:56 AM · Feb 15, 2022 allocatable_bounds.f90
Bounds of a derived type array component are preserved when passed to procedure. 8:24 AM · Feb 14, 2022 lbound_assumed_shape.f90
Array lower bounds are not preserved when passed as assumed shape argument. 7:55 AM · Feb 14, 2022 lbound_assumed_shape.f90
How to reverse an array or character string 7:52 AM · Feb 13, 2022 reverse.f90
Character variables can be compared like numerical variables. 8:23 AM · Feb 12, 2022 compare_character.f90
Internal write to character variable too small to hold output causes run-time error. 7:34 AM · Feb 11, 2022 write_char.f90
Convert from strings to numbers and the reverse using internal READ and WRITE. 7:43 AM · Feb 10, 2022 internal_read_write.f90
spread(source, dim, ncopies) copies a SOURCE array NCOPIES times along dimension DIM. 6:55 AM · Feb 9, 2022 spread.f90
Concatenate arrays and scalars in an array constructor [] 7:11 AM · Feb 8, 2022 concatenate.f90
get_command() and get_command_argument() get command line arguments. 7:38 AM · Feb 7, 2022 get_command.f90
Demonstrate subroutine get_environment_variable(name,value) of Fortran 2003. 9:21 AM · Feb 6, 2022 get_env.f90
Document results with compiler_version(), compiler_options(), and other intrinsics. 8:23 AM · Feb 5, 2022 xpi.f90
Execute_command_line() can call gnuplot to display a plot during a run. 7:44 AM · Feb 4, 2022
Execute_command_line() to pass a command to the shell. 7:23 AM · Feb 3, 2022 execute.f90
Mistakes in Fortran 90 Programs That Might Surprise You, by Szymanski 7:00 AM · Feb 2, 2022
Setting the values of an array section 7:41 AM · Feb 1, 2022 truloc.f90
Vector subscript can be used for non-contiguous array sections. 7:51 AM · Jan 31, 2022 vector_subscript.f90
Polyhedron suggested compiler optimization options and Fortran 95 benchmarks 9:13 AM · Jan 30, 2022
Google foo filetype:f90 or foo filetype:f to find Fortran code with foo. 5:43 PM · Jan 29, 2022
A procedure can have an argument that is another PROCEDURE with an INTERFACE. 8:02 AM · Jan 29, 2022 trapezoid.f90
Call ieee_set_halting_mode() to set floating point conditions that halt program. 10:26 AM · Jan 28, 2022 ieee_exceptions.f90
IEEE_ARITHMETIC module has functions to test numerical conditions. 9:22 AM · Jan 27, 2022 ieee_arithmetic.f90
Dummy argument that is changed must be definable in the caller. 7:20 AM · Jan 26, 2022 definable_arg.f90
ALLOCATABLE INTENT(OUT) argument is deallocated. 7:47 AM · Jan 25, 2022 intent_out_allocatable.f90
An INTENT(OUT) argument is undefined at the beginning of a procedure 7:45 AM · Jan 24, 2022 intent_out_undefined.f90
Turn compiler warnings into errors to force code defects to be fixed. 7:58 AM · Jan 23, 2022 warnings.f90
VALUE attribute for procedure arguments introduced in Fortran 2003 8:05 AM · Jan 22, 2022 value.f90
Use INTRINSIC to specify that compiler-provided procedures and modules are referenced 8:23 AM · Jan 21, 2022 intrinsic.f90
PROTECTED module variables cannot be changed outside the module. 7:12 AM · Jan 20, 2022 protected.f90
Array constructor with [] was introduced in Fortran 2003. Still valid is (//) 7:09 AM · Jan 19, 2022
Impure elemental procedure can be used to generate array of non-uniform variates 8:26 AM · Jan 18, 2022 random_normal.f90
Fortran 2008 introduced IMPURE ELEMENTAL procedures 8:07 AM · Jan 17, 2022 impure_elemental.f90
List of Fortran compilers, build tools, text editors, etc. 8:42 AM · Jan 16, 2022 list
Use iostat and iomsg to handle READ errors 7:14 AM · Jan 16, 2022 iomsg.f90 ; data_file
An unqualified USE foo statement imports public entities defined in foo and what foo imported. 7:29 AM · Jan 15, 2022 imports.f90
Module entities are PUBLIC by default. 7:45 AM · Jan 14, 2022 private.f90
How to rename an imported module entity 7:01 AM · Jan 13, 2022 rename.f90
Use the same name for analogous procedures defined in different modules using an INTERFACE 7:52 AM · Jan 12, 2022 shared_interface.f90
Procedures can be called with a mix of named and positional arguments. 8:26 AM · Jan 11, 2022 arguments.f90
UnALLOCATED variable passed to a procedure is not PRESENT there. 11:59 AM · Jan 10, 2022
DIMENSION can be used to declare several arrays of the same SHAPE 8:00 AM · Jan 9, 2022 dimension.f90
Propagation of an optional argument 8:23 AM · Jan 8, 2022 optional_use.f90
Two types of syntax for defining a function 9:28 PM · Jan 7, 2022 function.f90 function.txt
Syntax for character array without manual padding 11:19 AM · Jan 7, 2022 character_array.f90
Intrinsic character functions 4:58 AM · Jan 7, 2022 string_func.f90
Substrings of character variable arrays 11:31 AM · Jan 6, 2022 substring.f90
Parenthesize a variable to copy it "on the fly". 7:44 AM · Jan 6, 2022 overlapping_arg.f90
Use integer powers when possible. 11:28 AM · Jan 5, 2022 pow_real.f90
Use d0 or _kind to make a constant double precision. 8:02 AM · Jan 5, 2022 precision.f90
KIND numbers of types are not portable across compilers and should not be used directly. 7:39 PM · Jan 4, 2022
Avoid implicit save 8:50 AM · Jan 4, 2022 implicit_save.f90 run
Use parameters to dimension fixed-size arrays to make a code easier to change 6:45 AM · Jan 4, 2022
Fortran 2008 introduced z%re and z%im as alternatives to real(z) and aimag(z) 7:24 PM · Jan 3, 2022 im_re.f90
KindFinder code finds all KIND Values implemented by a compiler 10:47 AM · Jan 3, 2022 kindfind.f90
Real and integer KIND constants from iso_fortran_env; HUGE() and TINY() 7:51 AM · Jan 3, 2022 iso_kinds.f90
Advance="no" specifier of WRITE 6:47 PM · Jan 2, 2022 advance_no.f90
Len of character variable function result can depend on arguments 8:27 AM · Jan 2, 2022 join.f90
How size of an array function result can depend on function arguments 6:42 AM · Jan 2, 2022 array_func.f90
List of the syntax and purpose of Fortran intrinsics, with usage examples 11:46 AM · Jan 1, 2022
Do case-insensitive string comparisons by converting to lower case 9:00 AM · Jan 1, 2022 lower_case.f90
Fortran-lang suggested variable naming conventions 9:16 AM · Jan 1, 2022
Case insensitivity 10:49 AM · Jan 1, 2022 case_insensitivity.f90
Returning multiple values from a subroutine or function 8:20 PM · Dec 30, 2021 subroutine_dt.f90
MODULO vs. MOD function 7:13 AM · Dec 30, 2021
Compiler Support for the Fortran 2008 and 2018 Standards 1:59 PM · Dec 29, 2021
Many compilers evaluate ALL(x==y) efficiently with short-circuiting 12:16 PM · Dec 29, 2021
LEN of a character variable may be deferred in Fortran 2003 on 8:41 AM · Dec 29, 2021 deferred_character.f90
To learn about Fortran beyond F95, read the New Features articles of John Reid 5:18 AM · Dec 29, 2021
Use .true. and .false. for Booleans, not 1 and 0 1:04 PM · Dec 28, 2021
Standards committee has approved conditional expressions 8:47 AM · Dec 28, 2021
ANY and ALL may not be the most efficient methods to compare arrays. 8:02 AM · Dec 28, 2021
Consider using a tolerance to compare floats 7:51 AM · Dec 28, 2021 compare_floats.f90
Use ALL(A==B) to test for array equality 7:33 AM · Dec 28, 2021 all_any.f90
Intel Fortran Compiler (ifx) 9:52 AM · Dec 27, 2021
Doubled delimiter in a string is regarded as a single character of the constant 7:07 AM · Dec 27, 2021 doubled_delim.f90
Store data as an array of derived types or a derived type with array components? 9:55 AM · Dec 26, 2021 derived_type_array.f90
Fortran is column-major 4:22 AM · Dec 26, 2021 column_major.f90
CMPLX should be used with a KIND argument 6:30 PM · Dec 24, 2021 cmplx.f90
RESHAPE with the optional ORDER and PAD arguments 9:00 AM · Dec 24, 2021 reshape_array.f90
Use GAMMA to compute factorials 6:35 AM · Dec 24, 2021 factorial.f90
Derived type definition, initialization, and operator overloading 6:04 PM · Dec 23, 2021 date.f90
List-directed vs. explicitly formatted output 1:52 PM · Dec 23, 2021
Fortran equivalents of NumPy 4:08 AM · Dec 23, 2021
Zero-size array constructor such as [real ::] 8:51 PM · Dec 22, 2021 zero_size.f90
Use G0.d and colon edit descriptors with infinite repeat count to write delimited (CSV, etc.) output 9:44 AM · Dec 22, 2021
If allocation errors must be handled, use ALLOCATABLE rather than automatic arrays in procedures 6:48 AM · Dec 22, 2021 automatic.f90
Name modules and the source files containing them consistently, with one module per file. 11:13 AM · Dec 21, 2021
Use unformatted stream of Fortran 2003 for large-scale I/O. 5:59 AM · Dec 21, 2021 stream_io.f90
Using READ and WRITE for file i/o 12:38 PM · Dec 20, 2021 read_write_file.f90
Reading user input 8:47 AM · Dec 20, 2021 read_sum.f90
SELECT CASE for conditional execution 8:02 AM · Dec 20, 2021 select_case.f90
Declare floating point variables with KINDs 9:32 PM · Dec 19, 2021 kind.f90
Replace non-standard REAL*8 declaration with REAL(KIND=REAL64) 9:35 PM · Dec 19, 2021
Use PARAMETERs in modules to define physical and mathematical constants 6:00 PM · Dec 19, 2021 module_parameter.f90
Procedures can be RECURSIVE 4:56 PM · Dec 19, 2021
Specify function and subroutine argument INTENTs 4:39 PM · Dec 19, 2021
Subroutines can have INTENT(IN OUT) arguments, but functions should not 4:34 PM · Dec 19, 2021 intent_in_out.f90
Define and call a subroutine 4:16 PM · Dec 19, 2021 subroutine.f90
Demonstrate optional arguments and RANDOM_NUMBER 3:44 PM · Dec 19, 2021 optional.f90
Function overloading using an interface with module procedures 12:05 PM · Dec 19, 2021 interface.f90
USE, ONLY to avoid polluting the namespace 11:04 AM · Dec 19, 2021
Put functions and subroutines in modules to ensure that interfaces are checked. 10:50 AM · Dec 19, 2021 module.f90
ELEMENTAL functions broadcast arguments 10:37 AM · Dec 19, 2021 elemental.f90
Functions should be PURE and have INTENT(IN) arguments 10:25 AM · Dec 19, 2021 func.f90
PACK selects elements 10:13 AM · Dec 19, 2021 count_pack.f90
Loop variable equals the upper bound plus the stride after normal completion of a loop 10:04 AM · Dec 19, 2021 do_loop_index.f90
Associate creates an alias for expressions or variables. 7:52 AM · Dec 19, 2021 assoc.f90
In addition to if-elseif, Fortran has a one-line if 6:36 PM · Dec 18, 2021 one_line_if.f90
Character variables are padded with spaces at the end if necessary. 8:18 AM · Dec 18, 2021
An array of character variables has elements of the same LEN(gth). 8:10 AM · Dec 18, 2021 char.f90
MERGE(x,y,condition) returns x if condition is true, otherwise y 8:01 AM · Dec 18, 2021 merge.f90
IF-ELSEIF-ENDIF block 7:50 AM · Dec 18, 2021 if.f90
New Fortran code should be written using free source form and stored in a file with the .f90 suffix. 6:36 AM · Dec 18, 2021
Fortran has allocation on assignment. 6:26 AM · Dec 18, 2021 alloc.f90
SUM and other array functions have an optional DIM(ension) argument. 7:40 PM · Dec 17, 2021 2d_array.f90
Fortran arrays can have any lower bound. The default is 1. 6:16 PM · Dec 17, 2021 bounds.f90
Fortran array sections contain both endpoints 6:01 PM · Dec 17, 2021 sections.f90
Array intrinsic functions: SUM, MINVAL, MAXVAL, MINLOC, FINDLOC 5:44 PM · Dec 17, 2021 array_intrinsics.f90
Integer division truncates. 2:14 PM · Dec 17, 2021
** is the exponentiation operator. 12:03 PM · Dec 17, 2021 power.f90
Fortran compilers and tutorials 11:37 AM · Dec 17, 2021
EXIT a loop 11:30 AM · Dec 17, 2021 sum_exit.f90
DO-ENDDO loop 11:14 AM · Dec 17, 2021 loop.f90
Intrinsic data types: integer, real, complex, logical, and character 11:09 AM · Dec 17, 2021
Hello World 10:58 AM · Dec 17, 2021 hello_world.f90

fortrantip's People

Contributors

beliavsky avatar samharrison7 avatar shahmoradi avatar zmoon avatar zoziha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

fortrantip's Issues

Tip: searching GitHub for Fortran code

You can search for Fortran code on GitHub by entering, for example,
language:fortran topic:finite-elements in the search box. Topics are
lower case, have hyphens instead of spaces, and must be matched
exactly, so adding "s" to a topic gives different results.

Tweet automation?

Thinking about zmoon/FortranTipBrowser#2, with that kind of workflow it would be possible1 to automate the Tweet creation.

The text file format could be like:

The tweet text for the tip could be here at the top.

Maybe with multiple paras.

Long version
============
This would be the long version of the tip text.
This section (including heading) would be optional.

It can have multiple paras too.

Another option would be to place the tip text for the tweet and optional long version as comments in the Fortran source code file, would just have to decide on a format to use.

Footnotes

  1. I just got a Twitter API key, and there are some options for automating Carbon. I could write a GitHub Actions Workflow to check for new .f90/.txt files upon push to the main branch and create a draft tweet if one is found.

converting between strings and numbers

Convertings between Strings and numbers

Type conversion from strings to number and vice-versa is most commonly done
with internal reads and writes. You can read and write from a CHARACTER
variable as with a file. There is no direct way to read or write from an
allocatable array currently, so you have to use a variable of a defined
length.

Converting simple values

     program internal_io
     implicit none
     character (len=80) :: line
     real               :: value
     integer            :: ios
     character(len=256) :: message
     line='123.4e2'
     read(line,*,iostat=ios,iomsg=message) value
     if(ios.ne.0)then
        write(*,*)'ERROR: could not obtain numeric value from '//trim(line)
        write(*,*)'     : '//trim(message)
     else
        write(*,*)'VALUE=',value
     endif
     write(line,'("[",g0,"]")')1.0d0/3.0d0
     write(*,*)'line=',trim(line)
     end program internal_io

Results:

    VALUE=   12340.00    
    line=[.3333333333333333]

Tip: implied do loop

An implied do loop can be used to set the values of an array in one
line and to access array elements in a READ or WRITE statement, but
sometimes a whole-array operation suffices. It can also be used to print
a variable repeatedly.

program implied_do_loop
implicit none
integer, parameter :: n = 3
character (len=5)  :: words(n) = ["one ","four","nine"]
integer            :: vec(n),i
write (*,"(*(a,1x))") words ! one   four  nine
write (*,"(*(a,1x))") (trim(words(i)),i=1,size(words)) 
! one four nine -- one space between trimmed words
! write (*,"(*(a,1x))") trim(words) ! illegal since trim is not elemental
vec = [(i**2,i=1,n)] ! set to [1, 4, 9]
print*,vec ! 1 4 9
print*,(vec(i),i=1,n) ! same output, but simpler to use line above
! Implied do loop can have multiple entities:
print"(*(i0,1x,a,:,1x))",(vec(i),trim(words(i)),i=1,n) ! 1 one 4 four 9 nine
! print one element of vec and words on each line using "format reversion"
print"(i0,1x,a)",(vec(i),trim(words(i)),i=1,n) 
! Line above equivalent to loop below:
do i=1,n
   print"(i0,1x,a)",vec(i),trim(words(i))
end do
print "(*(1x,f0.2))",(3.14,i=1,3) ! 3.14 3.14 3.14
end program implied_do_loop
! output:
! one   four  nine 
! one four nine
!            1           4           9
!            1           4           9
! 1 one 4 four 9 nine
! 1 one
! 4 four
! 9 nine
! 1 one
! 4 four
! 9 nine
! 3.14 3.14 3.14

partially reading a list using list-directed I/O

List-directed input (using an asterisk("*") as a format) is often
described simply as free-format input but it is more. It allows for
null values and reading a partial list , and the form" r*c" where “r” is a repeater.

Suppose you have a program that prompts you for nine values to translate, scale, and/or rotate an object.

program listdirected
implicit none 
real :: x=0.0,y=0.0,z=0.0,  sx=1.0,sy=1.0,sz=1.0, rx=0.0,ry=0.0,rz=0.0
integer :: ios
character(len=256) :: msg, input
   do
      print *, 'Enter transformation value(s) or "stop"'
      print *, 'translate .........',x,y,z
      print *, 'scale .............',sx,sy,sz
      print *, 'rotate (degrees)...',rx,ry,rz
      read(*,'(a)',iostat=ios,iomsg=msg) input
      if(input.eq.'stop')exit
      read(input,*,iostat=ios,iomsg=msg) x,y,z,sx,sy,sz,rx,ry,rz
      if(ios.ne.0)then
         print *,"<ERROR>",trim(msg)
         cycle
      endif
      ! do something
   end do
end program listdirected

You do not have to enter all nine values. To just change all the scaling values to "2.0", you can enter:

  ,,,2,2,2/

Where the null values mean to skip changing that value, and the slash means the end of values, or equivalently

3*,3*2.0/

Where "3*" skips three values, 3*2.0" sets the next three values to two, and the "/" means you are done supplying values.

Using the minimal memory for large logical arrays

According to the Fortran standard, a nonpointer scalar object that is
default integer, default real, or default logical occupies a single
numeric storage unit, This often means a default logical value occupies
32 bits even though it is often thought of as a 1-bit boolean.

Many compilers support logical kinds that require less storage. If you
use large arrays of logical type you can see a significant reduction in
your memory footprint by using kinds that use less bits.

The default kind is sometimes faster, but because less bits are required
for smaller kinds the opposite may be true. Timing tests will tell you,
but you may see a performance gain as well (and you want to test to make
sure any change in kind is acceptable at all levels).

list available kinds

program whatkinds
use ISO_FORTRAN_ENV, only : logical_kinds
implicit none
   write(*,*)'! logical kinds are ',logical_kinds
end program whatkinds

You will typically find a KIND=1 is supported that
takes 8 bits, and that the default will be 32 bits.

list storage for a specified KIND

program whatsizes
implicit none
character(len=*),parameter :: g='(*(g0))'
integer,parameter :: VALUE=1 ! use KIND values you found
logical(kind=VALUE) :: boolean
   write(*,g)"kind=",kind(boolean),",bits=",storage_size(boolean)
   write(*,g)"kind=",kind(.true.),",bits=",storage_size(.true.),"(default)"
end program whatsizes

typical output ...

kind=1,bits=8
kind=4,bits=32(default)

So in that case you can have the same functionality using 1/4 the memory
by using a non-default kind.

Tip: integer division

Given integer variables i and j write

real(i,wp)/j or i/real(j,wp) or real(i,wp)/real(j,wp)

where wp is the KIND argument to get a real(kind=wp) quotient, unless
you want the truncating integer division resulting from

i/j

In Fortran 1/2 = 0.

partially reading a list using list-directed input

List-directed input (using an asterisk("*") as a format) is often
described simply as free-format input but it is more. It allows for
null values and reading a partial list , and the form" r*c" where “r” is a repeater.

Suppose you have a program that prompts you for nine values to translate, scale, and/or rotate an object.

program listdirected
implicit none 
real :: x=0.0,y=0.0,z=0.0,  sx=1.0,sy=1.0,sz=1.0, rx=0.0,ry=0.0,rz=0.0
integer :: ios
character(len=256) :: msg, input
   do
      print *, 'Enter transformation value(s) or "stop"'
      print *, 'translate .........',x,y,z
      print *, 'scale .............',sx,sy,sz
      print *, 'rotate (degrees)...',rx,ry,rz
      read(*,'(a)',iostat=ios,iomsg=msg) input
      if(input.eq.'stop')exit
      read(input,*,iostat=ios,iomsg=msg) x,y,z,sx,sy,sz,rx,ry,rz
      if(ios.ne.0)then
         print *,"<ERROR>",trim(msg)
         cycle
      endif
      ! do something
   end do
end program listdirected

You do not have to enter all nine values. To just change all the scaling values to "2.0", you can enter:

  ,,,2,2,2/

Where the null values mean to skip changing that value, and the slash means the end of values, or equivalently

3*,3*2.0/

Where "3*" skips three values, 3*2.0" sets the next three values to two, and the "/" means you are done supplying values.

Some files not mentioned

I am working on some parsing of this repo's readme and file list to help automate FTB. I found some programs that are in the repo but not linked to in the index, and one program that is mentioned in the readme but not present in the repo:

Not mentioned:

  • 2d_array.f90
  • alloc.f90
  • array_intrinsics.f90
  • assoc.f90
  • bitwise.f90
  • bounds.f90
  • char.f90
  • count_pack.f90
  • do_loop_index.f90
  • elemental.f90
  • func.f90
  • function.f90
  • hello_world.f90
  • if.f90
  • implicit_save.f90
  • input_data.f90
  • loop.f90
  • merge.f90
  • module.f90
  • naming.txt
  • one_line_if.f90
  • operators.f90
  • power.f90
  • sections.f90
  • shortest_code.f90
  • sum_exit.f90
  • trim.f90

Mentioned in the readme but not present in the repo:

  • precision.f90

Tip: assumed type argument

Fortran 2018 allows assumed type arguments that have no declared type,
with syntax type(*). Such arguments can only be used in a small number
of intrinsic functions, including SHAPE, SIZE, and RANK. Actual
arguments can have intrinsic or derived types.

module test_assumed_type_mod
implicit none
contains
pure function same_shape(x,y) result(tf)
! assumed type, assumed rank arguments
type(*), intent(in) :: x(..),y(..)
logical             :: tf
if (rank(x) /= rank(y)) then
   tf = .false. ! not same shape if ranks differ
else
   tf = all(shape(x) == shape(y))
end if
end function same_shape
end module test_assumed_type_mod
!
program test_assumed_type
use test_assumed_type_mod, only: same_shape
implicit none
type :: date
   integer :: year, month, day
end type date
integer    :: i(2),j(2,1)
real       :: x(2)
logical    :: b(3)
type(date) :: d(2)
print*,same_shape(i,x),same_shape(i,b), &
       same_shape(x,b),same_shape(i,d)
print*,same_shape(j,i),same_shape(j,x)
end program test_assumed_type
! output with gfortran and Intel Fortran:
! T F F T
! F F

Tip: a function can return a deferred-length character variable

You cannot write to an unallocated deferred-length (DL) character string,
but you can create a function that allocates a DL string, writes to it,
and then TRIMs it. One use is to convert an integer or real to a
deferred length string of minimal size..

module to_string_mod
implicit none
interface to_string
   module procedure to_string_int,to_string_real
end interface to_string
contains
!
pure function to_string_int(i) result(str)
integer, intent(in) :: i
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
write (str,"(i0)") i
str = trim(str)
end function to_string_int
!
pure function to_string_real(x,fmt) result(str)
real, intent(in) :: x
character (len=*), intent(in), optional :: fmt 
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
if (present(fmt)) then
   write (str,fmt) x ! use specified format
else
   write (str,"(f0.6)") x ! use default format
end if
str = trim(str)
end function to_string_real
!
end module to_string_mod
!
program test_to_string
use to_string_mod, only: to_string
implicit none
print "(*(:,'''',a,'''',:,1x))", to_string(-123), &
  to_string(3.14),to_string(3.14,"(f0.2)")
! two consective quotes inside quotes treated 
! as single quote
end program test_to_string
! output:
! '-123' '3.140000' '3.14'

Tip: gfortran -fdump-tree-original

gfortran -c -fdump-fortran-original -fdump-tree-original a.f90
prints the internal representation of the Fortran abstract syntax tree
to standard output and writes a C-like representation that is passed
to the middle end.

Tip: named if block

An if block can be named, for example

name: if (x > 0) then
   print*,"+"
else
   print*,"-"
end if name

One use besides documentation is to skip code outside of an inner if block when if blocks are nested,
by exiting the outer if block.

program named_if_block
implicit none
real :: x
integer :: i
do i=1,10
   call random_number(x)
   test_big: if (x > 0.5) then
      if (x > 0.9) then
         print*,x," is very big"
      else if (x > 0.8) then
         print*,x," is quite big"
      else
         print*,x," is big"
         exit test_big
      end if
      print*,"x**2=",x**2 ! execute if x > 0.8
   else
      print*,x," is small"
   end if test_big
end do
end program named_if_block

Sample output:

  0.567683935      is big
  0.790556431      is big
  0.631362140      is big
  0.144122779      is small
   4.83593345E-02  is small
  0.504784107      is big
  0.842326403      is quite big
 x**2=  0.709513783    
  0.790282488      is big
  0.906665266      is very big
 x**2=  0.822041929    
  0.454891980      is small

OOPS: Roundoff pitfalls

Roundoff pitfalls such as assigning a real to an integer, using MOD with REAL arguments, assigning a constant value without a type like A=1234567.0 ! sans d0 suffix
suggested by @urbanjost

Tip: nested implied do loop

Implied do loops can be nested, with syntax such as

print*,((m(i,j),j=1,n2),i=1,n1)

An application is to WRITE or READ array elements in an order other
than the default column-major order.

program nested_implied_do
implicit none
integer, parameter :: n = 2
integer :: i,j,m(n,n)
character (len=*), parameter :: fmt = "(*(i0,:,1x))"
m(1,:) = [11,12]
m(2,:) = [21,22]
print fmt,m ! 11 21 12 22 -- column major
print fmt,((m(i,j),j=1,n),i=1,n) ! 11 12 21 22 -- row major
print fmt,(m(i,:),i=1,n) ! same as above
print fmt,transpose(m) ! same as above, but transpose is
                       ! limited to 2D arrays
end program nested_implied_do

Tip: function can return deferred length character string

You cannot write to an unallocated deferred-length (DL) character string,
but you can create a function that allocates a DL string, writes to it,
and then TRIMs it. One use is to convert an integer or real to a
deferred length string of minimal size

module to_string_mod
implicit none
interface to_string
   module procedure to_string_int,to_string_real
end interface to_string
contains
!
pure function to_string_int(i) result(str)
integer, intent(in) :: i
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
write (str,"(i0)") i
str = trim(str)
end function to_string_int
!
pure function to_string_real(x,fmt) result(str)
real, intent(in) :: x
character (len=*), intent(in), optional :: fmt 
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
if (present(fmt)) then
   write (str,fmt) x ! use specified format
else
   write (str,"(f0.6)") x ! use default format
end if
str = trim(str)
end function to_string_real
!
end module to_string_mod
!
program test_to_string
use to_string_mod, only: to_string
implicit none
print "(*(:,'''',a,'''',:,1x))", to_string(-123), &
  to_string(3.14),to_string(3.14,"(f0.2)")
! two consective quotes inside quotes treated 
! as single quote
end program test_to_string
! output:
! '-123' '3.140000' '3.14'

The missing factorial function

Why does Fortran not have a factorial function?

It does, as for positive whole values of X the Gamma
function simplifies to the factorial function for (X-1).
That is,

x! == gamma(x+1)
program testit
use, intrinsic :: iso_fortran_env, only : wp=>real64
integer,parameter :: n(*)=[0,1,5,11,170]
integer :: j

   do j=1,size(n)
      write(*,'(*(g0,1x))')'factorial of', n(j),' is ', &
       & product([(real(i,kind=wp),i=1,n(j))]),         &
       & ' or ',                                        &
       & gamma(real(n(j)+1,kind=wp))
   enddo

end program testit

Tip: many-one vector subscripts can be used but not on the LHS

A vector subscript can have repeated elements, creating a many-one section,
for example

x([1,2,1])

Such a section must not appear on the left hand side of an assignment, because of
the ambiguity, but some compilers do not catch this.

program many_one
implicit none
integer, parameter :: ncou = 4
character (len=6)  :: continents(2) = ["Asia  ","Europe"]
character (len=6)  :: countries(ncou) = &
   ["France","Japan ","China ","Italy "]
integer            :: ic(ncou) = [2, 1, 1, 2]
character (len=*), parameter :: fmt = "(*(a10))"
print fmt, "country",countries
print fmt, "continent",continents(ic) 
! line above is a valid many-one section
! line below is invalid since many-one array section
! must not appear on left hand side
continents(ic) = ["a","b","c","d"]
print fmt, continents
end program many_one
! gfortran and Intel Fortran output is below.
! They do not catch the invalid many-one assignment.
!
!    country    France    Japan     China     Italy 
!  continent    Europe    Asia      Asia      Europe
!    c         d 

Tip: assumed rank argument

Fortran 2018 has assumed rank arguments, denoted x(..), that can be a scalar or an array
of arbitrary rank. Within the procedure the SELECT RANK construct and RANK intrinsic
is used to handle each rank.

module m
implicit none
public :: mean,avg
! older way to have same name for function with multiple ranks
! is an interface with module procedures
interface avg
   module procedure avg_0,avg_1,avg_2
end interface avg
contains
function mean(x) result(y)
real, intent(in) :: x(..) ! assumed rank argument
real             :: y
select rank (x)
   rank (0)     ; y = x ! scalar case
   rank (1)     ; y = sum(x)/max(1,size(x))
   rank (2)     ; y = sum(x)/max(1,size(x))
   rank default ; stop "mean not impelemented for rank > 2"
end select
end function mean
!
function avg_0(x) result(y) ! rank 0 argument
real, intent(in) :: x
real             :: y
y = x
end function avg_0
!
function avg_1(x) result(y) ! rank 1 argument
real, intent(in) :: x(:)
real             :: y
y = sum(x)/max(1,size(x))
end function avg_1
!
function avg_2(x) result(y) ! rank 2 argument
real, intent(in) :: x(:,:)
real             :: y
y = sum(x)/max(1,size(x))
end function avg_2
end module m
!
program test_assumed_rank
use m, only: avg  ! interface with module procedures
use m, only: mean ! function with assumed rank argument
implicit none
integer, parameter :: n1 = 1000, n2 = 5
real :: x(n1,n2)
character (len=*), parameter :: fmt="(*(f6.3))"
call random_seed()
call random_number(x)
! demonstrate rank 0, 1, 2 cases
print "(*(a6))","avg","mean","check"
print fmt,avg(x(1,1)),mean(x(1,1)),x(1,1)
print fmt,avg(x(:,1)),mean(x(:,1)),sum(x(:,1))/n1
print fmt,avg(x),mean(x),sum(x)/(n1*n2)          
end program test_assumed_rank
! works with gfortran and Intel Fortran
! sample output:
!    avg  mean check
!  0.662 0.662 0.662
!  0.507 0.507 0.507
!  0.506 0.506 0.506

Tip: print*,char(7) to beep

In ASCII and Unicode the character with the value 7 is BEL, so

print*,char(7)

will cause the program to beep, which can be used to signal completion.

Tip: derived type can have derived type components

A derived type may have components that are also derived types. If x
is an instance of a derived type that has component y, and y has
component z, you can write x%y%z to access z. A similar syntax applies
with type extension of Fortran 2003.

module m
implicit none
type :: date_t
   integer :: year, month, day
end type date_t
type :: daily_temperature_t
   type(date_t) :: date
   real :: high, low
end type daily_temperature_t
end module m
!
program derived_type_composition
use m, only: daily_temperature_t, date_t
implicit none
type(daily_temperature_t) :: x
character (len=*), parameter :: fmt = "(*(1x,g0))"
! use default constructors of daily_temperature_t and date_t
x = daily_temperature_t(date_t(2022,2,12),high=30.0,low=10.0)
print fmt,x ! 2022 2 12 30.0000000 10.0000000
print fmt,x%date%year ! 2022
end program derived_type_composition

Tip: derived types can be used where scalars are required

An instance of a derived type is a scalar, even if it has array or
pointer components. A derived type can be used where a scalar is
required, for example as the dummy argument of an elemental procedure.
Arrays of arrays or pointers can thus be simulated.

module m
implicit none
type :: vec
   real, allocatable :: x(:)
end type vec
contains
function ran(n) result(xran)
integer, intent(in) :: n
real :: xran(n)
call random_number(xran)
end function ran
!
elemental function moment(v,m) result(xmom)
! return the nth moment of the array component of v
type(vec), intent(in) :: v
integer  , intent(in) :: m
real                  :: xmom
real                  :: xmean
integer               :: n
n = max(1,size(v%x))
xmean = sum(v%x)/n
xmom  = sum((v%x-xmean)**m)/n
end function moment
end module m
!
program main
use m, only: moment,vec
implicit none
type(vec) :: v
character (len=20) :: fmt = "(a6,*(f8.4))"
v = vec(x = ran(10**4))
print fmt,"sim",moment(v,[1,2,3,4])
print fmt,"true",0.0,1/12.0,0.0,1/80.0
end program main
! sample output:
!    sim -0.0000  0.0833  0.0001  0.0124
!   true  0.0000  0.0833  0.0000  0.0125

Tip: growing array with move_alloc

this tip can be useful for simulating systems that change size on the fly, for example

program main
  implicit none
  integer, allocatable :: matrix(:,:)
  integer, allocatable :: temporary(:,:)
  integer :: old_rows, old_cols, new_cols
  integer :: i, j, n
 
  old_rows=3
  old_cols=3
  n=3
 
 allocate(matrix(old_rows,old_cols),source=0)
 
  do j = 1, old_rows
     write(*,*) matrix(j,:)
  end do
 
  do i = 1, n
      new_cols=old_cols+1
 
      allocate(temporary(old_rows,new_cols),source=1)
      temporary(1:old_rows,1:old_cols) = matrix(1:old_rows,1:old_cols)
 
      call move_alloc(from=temporary,to=matrix)
 
      write(*,*)
      do j = 1, old_rows
         write(*,*) matrix(j,:)
      end do
  
      old_cols=new_cols
    end do
  
 end program main

output

000
000
000

0001
0001
0001

00011
00011
00011

Tip: bounds of assumed shape arrays

The lower bounds of an assumed shape dummy argument are 1 or the lower bounds specified in the
procedure declaration, regardless of the lower bounds of actual argument in the caller. Lower
bounds of a derived type array component are preserved.

module bounds_mod
implicit none
type :: vec
   real :: x(0:2)
end type vec
character (len=*), parameter :: fmt = "(a30,*(1x,i4))"
contains
subroutine print_bounds(x)
real, intent(in) :: x(:)
print fmt,"in print_bounds, bounds =",lbound(x),ubound(x)
end subroutine print_bounds
!
subroutine print_bounds_0(x)
real, intent(in) :: x(0:)
print fmt,"in print_bounds_0, bounds =",lbound(x),ubound(x)
end subroutine print_bounds_0
!
subroutine print_bounds_mat_3_5(x)
real, intent(in) :: x(3:,5:)
print fmt,"in print_bounds_0, bounds =",lbound(x),ubound(x)
end subroutine print_bounds_mat_3_5
!
subroutine print_bounds_vec(v)
type(vec), intent(in) :: v
print fmt,"in print_bounds_vec, v%x bounds =",lbound(v%x),ubound(v%x)
end subroutine print_bounds_vec
end module bounds_mod
!
program main
use bounds_mod
implicit none
real :: x(0:3),xmat(-1:5,2:4)
type(vec) :: v
print fmt,"in main, bounds =",lbound(x),ubound(x)
call print_bounds(x)
call print_bounds_0(x)
print fmt,"in main, bounds =",lbound(xmat),ubound(xmat)
call print_bounds_mat_3_5(xmat)
print fmt,"in main, v%x bounds =",lbound(v%x),ubound(v%x)
call print_bounds_vec(v)
print "(/,a)","calling print_bounds with v%x"
call print_bounds(v%x)
end program main
! output:
!              in main, bounds =    0    3
!      in print_bounds, bounds =    1    4
!    in print_bounds_0, bounds =    0    3
!              in main, bounds =   -1    2    5    4
!    in print_bounds_0, bounds =    3    5    9    7
!          in main, v%x bounds =    0    2
! in print_bounds_vec, v%x bound    0    2
! 
! calling print_bounds with v%x
!      in print_bounds, bounds =    1    3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.