TweetFollow Us on Twitter

Volume Number:1
Issue Number:11
Column Tag:Fortran's World

Fractuals in Fortran 2.1

By Chuck Bouldin, Physicist, National Bureau of Standards

A Look at MacFortran 2.1

Last month's issue contained a first look at Macfortran, an implementation of FORTRAN on the Macintosh. This article is intended to continue that discussiion, and specifically to look at the new features in the 2.1 release of Macfortran and to begin to explore the Macfortran interface to the Toolbox routines. This article will describe the new Toolbox capabilities in the 2.1 release, the extensions and improvements to FORTRAN in 2.1 and give a couple of short examples which begin to show how Macfortran interacts with the Macintosh environment. It will discuss the strengths (and weaknesses) of this implementation of FORTRAN, and show what this language can accomplish on the Macintosh.

Why Fortran?

One of the first things to determine about any computer language is the class of problems for which it is best suited. There are lots of languages now available for the Macintosh; we need to determine where FORTRAN fits into the hierarchy of tools available for programming the Mac. Please note that this is not intended to continue the meaningless debate about the 'best' computer language, rather this intended to be a (reasonably) realistic assesment of FORTRAN as a tool on the Mac.

First of all, there exists a very clear definition of the language. The American National Standards Institute (ANSI) has published a document which completely defines the FORTRAN 77 language. Any implementation of the language must meet the standards defined by ANSI, or it really isn't FORTRAN. In the past, the main problem with microcomputer implementations of FORTRAN has been that they were incomplete, including only a part of the ANSI standard. MacFortran is a refreshing break from the past; it implements the full ANSI definition of the language. Since the language is so clearly defined, this makes for a remarkable degree of software portability. Code written in FORTRAN on any other machine, micro or mainframe, ports easily to the Macintosh. Obviously, Macintosh extensions such as Toolbox calls will not be of much use on other machines, but the other parts of the code are standard. Details on the Toolbox interface and porting FORTAN from other machines to the Mac are given later.

Second, MacFortran is the only fully compiled language for the Macintosh other than C. This means that when an application must run fast, then the high level language possibilities are C or FORTRAN. In some ways FORTRAN represents a natural upgrade from Basic when speed is a concern, since Basic was first derived as a subset of FORTRAN. Basic programmers who find they need faster running programs will probably find it easier to convert to FORTRAN than to learn C.

Third, if you crunch numbers, this is your language. MacFortran does not use SANE, the 80 bit software floating point built into the Mac. MacFortran has its own floating point; 32 bit single precision and 64 bit double precision. This floating point is fast, easily the fastest available on the Macintosh. Specific benchmarks are given below.

The language does has limitations, which show up mostly in the ancient lineage of FORTRAN. The most glaring limitation is the inability to create data types which correspond to Pascal records or C structures. The closest that MacFortran comes to this is simple arrays. This means that when dealing with complex data structures, the programmer, rather than the compiler, is forced to do some of the bookkeeping about where various data elements are located.

Toolbox Support

Of course the crucial element of a language for the Macintosh is how well it can interface to the Toolbox routines provided in the Mac ROMS. MacFortran provides direct access to almost all of the Toolbox routines, including Quickdraw, access to serial ports, Window and Menu creation, the font manager, the standard file package, Text edit, use of Desk accesories from inside FORTRAN programs, and more. Missing so far are access to the control and memory manager. Although not all of the Toolbox is directly supported from FORTRAN, MacFortran allows calls to assembly language subroutines which can obviously access any routine.

MacFortran calls Macintosh routines through a single subroutine, TOOLBX. The first parameter passed to this subroutine is an upper case character string which is the name of the Mac routine being called. The parameters which follow are the arguments that the Mac routine needs. TOOLBX is a 'glue' routine which takes care of putting the arguments onto the stack or into the cpu registers.

There is one main complication in using MacFortran to access Mac Toolbox routines. As mentioned earlier, FORTRAN does not support data types such as Pascal records or C structures. Since such data structures are used by many of the Toolbox routines, how can these routines be supported from MacFortran? The answer is simple, the data structures are just mapped onto a MacFortran array, and the array is then passed to TOOLBX, which handles the mapping from array elements onto stack locations or 68000 registers. With this type of approach, MacFortran can handle all of the Mac Toolbox with equal facility.

Using MacFortran

The MacFortran system comes with compiler, linker, librarian, and source code debugger. Apple's Edit and Rmaker programs are also included. The compiler and debugger have full Mac-style interfaces with pull-down menus and the usual dialogue boxes for file selection and compiler options. Suprisingly, the linker and librarian retain Unix type interfaces.

The compiler is organized into 3 overlays: (1) parsing and preliminary reduction of tokens into object code, (2) resolution of backwards jumps and some final code generation (3) setting up pointers for a runtime linkage. The overall compilation speed for large programs is 500-1000 lines/minute. Due to disc overhead swapping the compiler overlays, small programs (under 100 lines) will seem much slower, perhaps 50-200 lines/minute.

As mentioned above, the third compiler pass actually sets up pointers for a runtime link. In a program which does not call previously compiled subroutines this justs sets a pointer to load the MacFortran runtime library. At runtime, the library and any other needed subroutines, will be autoloaded when called. At runtime, first the default disc and then the internal disc are searched for needed subroutines. During development, this saves having to crank up the linker every time a change is made in the code. On the down side, subroutines are not locked in memory after they are called once; they are reloaded at each call. Clearly, you don't want runtime linking for subroutines which are called more than a few times. Also, the search path can lead to some confusion. If an application program is executed from the internal drive and the runtime library is in the external drive, the runtime library is not found, since the internal drive is now also the default drive. The internal drive is first searched as the internal drive and then as the default drive, missing the runtime library. [Isn't this a bug? -Ed.]

Easily the most impressive component of the package is the source code Debugger. This utility brings up a window of the MacFortran source code being debugged, a window to display variables and a 5 line MacFortran output window. The source code can be single stepped, breakpoints can be set and changed, and variables can be continuously monitored. This is almost like having a FORTRAN interpreter! Getting code working is very greatly simplified by this debugger.

The linker and librarian are certainly functional, but do not have a Macintosh type interface. The worst part of this is having to remember file names. On the plus side, the linker supports creation of 'scripts', files which contain canned linker 'programs'. This simplifies linking since many of the same libraries and subroutines are linked to different programs. According to Absoft there are two reasons for the non-Mac interface: (1) to provide the large table space that the linker needs and still fit into a 128K machine it was necessary to use a primitive interface, and (2) the interface remained unchanged in 2.1 since the programming effort was put into changing the linker to support linking on an entry point, rather than a filename basis. In 2.0, the ENTRY statement in FORTRAN was effectively disenfranchised since linking was done on only a filename basis. I still don't like the user interface, but the functionality of supporting the ENTRY statement is certainly more important. [In otherwords, the linker isn't finished yet! -Ed.]

The linker also makes no discrimination about what parts of the runtime library are actually used by a program; the entire library is linked in regardless. This means that the smallest MacFortran program will be about 18K, a real detriment to writing desk accessories in this language. On the other hand, several programs can be completely linked except for the runtime libary and share a single copy of the runtime library through runtime linking. Also, applications that do anything more involved than "hello, world" are likely to bring in large fractions of the Runtime library anyway. Runtime linking is certainly not required. The linker and librarian manage pre-compiled object code and standalone applications are easily created.

Portability Considerations

As mentioned earlier, one of the main attractions of FORTRAN is the portability of the language. I have ported several large applications down from a VAX 11/780 and have learned some of the pitfalls to watch out for when porting code down to the Mac. Since the use of existing code, particularly mathematical software, is a major incentive for using Macfortran, it is worth describing the portability considerations in detail. All of the non-portable code that I have downloaded to the Mac has turned out to be due to the use of non-standard features in VAX FORTRAN.

First, it is essential to use the SAVE statement in order to preserve variables between calls to a subroutine. This was mentioned in last months column, but the impression was given that this is a quirk of Macfortran. It is not. It is standard FORTRAN, although VAX and most mainframes do not require it. On a small machine such as the Macintosh, the use of the SAVE statement allows you to write larger programs by disposing of unneeded variable space. The main caution is that COMMON blocks must be SAVE-d between calls to a subroutine. This is conterintuitive, but it is standard FORTRAN.

Second, DATA statements must follow all declarations (REAL, COMPLEX, etc.). Again, this is standard FORTRAN, but is relaxed on most large machines. The main place to look out for this is when using INCLUDE statements to enter the COMMON variables in a group of subroutines that share COMMON blocks.

Third, watch out for READ/WRITE statements that use system dependent logical units. The way to avoid this problem is to use PARAMETER statements to assign logical units. For instance, to avoid the problems described last month with units 5 and 6 in Macfortran I use on the Macintosh:


On the VAX I use the same code, but set:


It is also possible to use the compiler option which maps READ* and PRINT* statements to unit 9 to resolve all the problems associated with list directed READ and WRITE statements.

Extensions and Enhancements in 2.1

The major news for the 2.1 revision is that the compiler has been licensed to Microsoft. This should mean that there will now develop a much larger user community for this language. In evaluating the 2.1 revision I have been working from a (slightly) modified version of the 2.0 documentation. According to Absoft, the new manual has been completely rewritten by Microsoft, and is much more Mac specific than the old documentation. The manual is 400 pages, organized into a Users guide and a Reference manual. It also reflects an orientation towards a less sophisticated user with less prior knowledge of FORTRAN.

In addition to Macintosh specific enhancements, there are some extensions in the Absoft FORTRAN which are very nice. Probably the most powerful is the addition of recursion to the language. Some programs are very difficult to write without recursion and are very natural when recursion is used. As an example of recursion, and to illustrate the drawing speed of Macfortran a short example which draws fractals is given below.

Other extensions include a CASE statement for multi-way branches, DO loops that are terminated with a REPEAT statement, and a generalized looping statement, WHILE(condition)....REPEAT. The WHILE statement is especially useful, since it gives much more flexible looping to FORTRAN; one no longer has to map all loops onto arithmetic progressions.

The compiler still operates in the same way as before. The user selects a file from the standard file box and then chooses among options such as Compile, Compile and Execute, Compile and Debug, etc. A nice human engineering change is that the compiler options can now be saved so that they do not need to be reset after every compile. The user still has to explicitly choose an option before anything happens. I do not find this flexibility confining.

The standard file package, Text edit utilities, and Desk accessory support (Systemclick and Systemtask) are now accessible from Fortran. The glaring things still missing are access to the Control and memory managers. By using the compile to assembly source to observe what code is generated for, say, the Window Manager it should be possible to figure out what to do for the Control Manager. It is aggravating to have to do this; hopefully we will soon get full documentation on all the Toolbox.

There is now a compiler option to map lower case onto upper case. This is very useful since only upper case characters are recognized by an ANSI standard compiler. Differences betwen VAX and Macfortran about character case have caused problems porting code. This option switch solves those problems.

There are several new demo programs, including a Fortran version of the Edit program from Inside Macintosh. On the subject of Edit, it is not Absoft's fault that the MDS Editor contains hardwired references to its transfer points. This is not even a resource that can be changed with the resource editor! Instead, references to EXEC, etc. are embedded in the code in the MDS Editor. The simple (but not elegant) solution is to rename Fortran as EXEC on the desktop. This allows transfers back and forth between Macfortran and Edit.

There is now access to the A5 register and Quickdraw globals via a call to GETGLOBALS.


As mentioned earlier, one reason for using this language is speed. The code is fully translated into 68000 object code for fast execution. For instance, the Sieve of Eratosthenes runs in 6.8 seconds, about as fast as Mac C compilers (without register variables). It is harder to find such universal benchmarks for floating point, but MacFortran executes single precision floating point 5-10 times faster than Mac languages that use the 80 bit SANE package. Some of the Mac C compilers also have their own floating point packages, but MacFortran is 2 times faster than the fastest of these.

To give some idea of floating point speed I ran two benchmarks that have had some runs on other machines (mostly IBM and clones). I ran Jerry Pournelle's benchmark which fills and multiplies two 20x20 matrices, with an execution time of 2.9 seconds. This is very fast, since an 8 Mhz 8088 with 8087 runs the same benchmark in 3.9 seconds using Pascal MT+. In addition, I ran the benchmark 'float' from the Aug, 85 issue of Byte magazine, page 133. Here, an IBM XT with 8087 recorded a time of 11.7 seconds using Microsoft Fortran and an IBM AT with an 80287 and Digital Research Fortran came in at 17.7 seconds. Using MacFortran, the Macintosh comes in at 7.7 seconds. When compared to a VAX 11/780 for large application programs such as matrix inversion, Fourier transforms, and optical ray tracing Macfortran delivers about 4-7% of the 780 performance. Of course, what a user cares about is how long he waits for the results. On a moderately loaded VAX I find that the difference in execution time drops to a factor of 2-5 between the Mac and the VAX.

I won't belabor the comparisons any more since the conclusion is clear; MacFortran is very, very fast for floating point operations. For a reasonable mix of floating and fixed point operations, MacFortran is at least as fast as any other language on the Mac. It is also faster than the main microcomputer competitor even when compared with hardware floating point. For crunching numbers, this language is unbeatable.

There are some caveats. The above benchmarks compare the default precision of each language. In MacFortran this is 32 bit single precision, providing only 5-6 decimal digits of accuracy, so is it 'fair' to compare this with the 80 bit software floating point of SANE or the 80 bit hardware floating point of the 8087? Yes, it is. Languages which do all floating point as 80 bit calculations give the user no choice, frequently providing more precision than is needed. In MacFortran you choose; if you need more accuracy, use double precision (64 bit), while if speed is the main concern, stay with single precision. Usually single precision is fine.

A Pair of Examples

The examples below are intended to illustrate a small part of the Macfortran interface to the Mac Toolbox routines. These show about the simplest level at which a FORTRAN program can interface with the Macintosh. The 'user interface' in these examples is not via Menus and dialogue boxes, but these routines do show off the graphics capability available from Macfortran and illustrate the use of recursion for drawing fractals (see Aug, 85 Macworld for the same example in MacPascal).

 program ranplt
* This illustrates the use of some Quickdraw routines for 
*  plotting on the screen and erasing areas of the screen. This
*  routine is intended to show the drawing speed on the screen
* and to illustrate the use of the internal random number
* generator, TOOLBX(RANDOM). Since the coordinate arrays
* are filled before plotting starts, this routine gives a measure
* of the raw plotting speed from inside Macfortran. Toolbox
*  routines used are:


* Storage for the starting position
* For random coordinates
      INTEGER*4 IXRAND(3000), IYRAND(3000)
* Declarations for calculating elapsed time for plot
* Include the Toolbox Call Parameter file.
* Rectangle stuff for erasing the screen
      DATA BIGRECT /0,0,512,512/
      DATA SMLRECT /0,0,60,100/

*Stuff default values for NSTEPS and ISCALE
      NSTEPS = 1000
      ISCALE = 6
* Set up number of steps and stepsize
      PRINT*, 'Number of steps ? (3000 maximum, 1000 default)'
      READ*,   NSTEPS
      PRINT*,'Approximate step size in pixels ? (5 default)'
      ISCALE = 32000 / ISCALE

* Clear the screen

* Get the starting time (in ticks)
* Note that this is a system global!

* Stuff the random coordinate arrays
* TOOLBX(RANDOM) returns a random integer between 
* -32768 and 32767, inclusive
      DO ( I=1,NSTEPS )

* Move to center of screen
        XSTART = ( BIGRECT(1) + BIGRECT(3) ) / 2
        YSTART = ( BIGRECT(2) + BIGRECT(4) ) / 2

* Draw the next line.
        DO ( I=1, NSTEPS )

* Get the ending time and print deltat
* Ending time in ticks
      TIME2 = LONG(362)
      DELTAT = (TIME2 - TIME1) / 60.

         program snowflake
* Draws a fractal pattern using Toolbox calls and recursion.
* Calls
      integer x1,y1,x2,y2,n
      integer xorig,yorig,scaling
      integer*2 rect(4)
      xorig = 250
      yorig = 230
      scaling = 100
      rect(1)=0; rect(2)=0; rect(3)=340; rect(4)=510
        call toolbx(ERASERECT,rect)
        call toolbx(MOVETO,3,12)
        type "order= (0 to quit)"; accept n
        if(order.eq.0) then 
           go to 20
        call toolbx(ERASERECT,rect)
        x1 =  xorig - scaling
        y1 =  yorig
        x2 =  xorig + scaling
        y2 =  yorig
        call snowr(x1,y1,x2,y2,n)
  20  continue  
      subroutine snowr(x1,y1,x12,y12,n)
      integer x1,y1,x12,y12,n
      integer xdiff,ydiff,x(2:12),y(2:12)
      s = 0.5573
      x(12) = x12
      y(12) = y12
      xdiff = x12 - x1
      ydiff = y12 - y1
      x(10) = x1 + xdiff/3
      y(10) = y1 + ydiff/3
      x(11) = x1 + xdiff*2/3
      y(11) = y1 + ydiff*2/3
      x(3)  = x(10) + ydiff*s
      y(3)  = y(10) - xdiff*s
      x(9)  = x(10) + ydiff*s/3.0
      y(9)  = y(10) - xdiff*s/3.0
      x(8)  = x(10) + ydiff*s*2.0/3.0
      y(8)  = y(10) - xdiff*s*2.0/3.0
      x(2)  = (x1+x(3))/2
      y(2)  = (y1+y(3))/2
      x(4)  = x(11) + ydiff*s
      y(4)  = y(11) - xdiff*s
      x(6)  = x(11) + ydiff*s*2.0/3.0
      y(6)  = y(11) - xdiff*s*2.0/3.0
      x(5)  = (x12+x(4))/2
      y(5)  = (y12+y(4))/2
      x(7)  = (x(8)+x(4))/2
      y(7)  = (y(8)+y(4))/2
      if (n=1) then
         call toolbx(MOVETO,x1,y1)
         do (i=2,11)
           call toolbx(LINETO,x(i),y(i))
         call toolbx(LINETO,x12,y12)
      call snowr(x(2),y(2),x1,y1,n-1)
      call snowr(x(2),y(2),x(3),y(3),n-1)
      call snowr(x(3),y(3),x(4),y(4),n-1)
      call snowr(x(4),y(4),x(5),y(5),n-1)
      call snowr(x(5),y(5),x(6),y(6),n-1)
      call snowr(x(7),y(7),x(6),y(6),n-1)
      call snowr(x(7),y(7),x(8),y(8),n-1)
      call snowr(x(9),y(9),x(8),y(8),n-1)
      call snowr(x(9),y(9),x(10),y(10),n-1)
      call snowr(x(11),y(11),x(10),y(10),n-1)
      call snowr(x(11),y(11),x(12),y(12),n-1)
    end if

Community Search:
MacTech Search:

Software Updates via MacUpdate

How to get more cars in CSR Racing 2
NaturalMotion and Zynga brought a lot of real life cars to the table for CSR Racing 2. From souped up everyday rides made by Nissan and Hyundai to supercars produced by the likes of McLaren and Pagani, there really is something for everyone. [... | Read more »
Crypt of the NecroDancer Pocket Edition...
Crypt of the NecroDancer Pocket Edition 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Crypt of the NecroDancer is an award winning hardcore roguelike rhythm game. Move to the music and... | Read more »
Gear-grinding puzzle title Inner Circle...
If you saw our post earlier this month announcing the imminent release of ZPlay’s new creation, Inner Circle, you’ll be happy to know that it’s now available on the App Store. Established in 2010, developer and publisher ZPlay have taken the... | Read more »
CSR Racing 2: Your guide to what's...
CSR Racing 2, or CSR2, as it likes to call itself, has finally arrived. The follow-up to the immensely popular drag racing game CSR Racing is the first release from NaturalMotion since the studio's acquisition by Zynga in early 2014. [Read more] | Read more »
Nanuleu (Games)
Nanuleu 1.1 Device: iOS Universal Category: Games Price: $2.99, Version: 1.1 (iTunes) Description: Nanuleu is a strategy game where you take control of ancient magical trees that protect the land from an invading dark force. A... | Read more »
The Slaughter: Act One (Games)
The Slaughter: Act One 1.0.323 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.323 (iTunes) Description: “The game mixes realism and surrealism to create a story that can cause just as much laughter as fear. A-” -... | Read more »
NEO TURF MASTERS 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: NEOGEO’s legendary golf game is back, in a brand-new mobile version with touch controls! NEO TURF MASTERS (also known as “BIG... | Read more »
How to send money to a friend with the F...
Facebook is already a lot of things to a lot of people. It's a social network, sure, but also a tool for catologing memories, chatting with friends, and much more. [Read more] | Read more »
Branch out into the Chinese market with...
Created a game that you’re super enthused about, only to find yourself struggling to get it the exposure that you believe it duly deserves? With the time, energy and money that goes into development, it’s only right that games should be given the... | Read more »
Pocket Arcade Story (Games)
Pocket Arcade Story 1.00 Device: iOS Universal Category: Games Price: $4.99, Version: 1.00 (iTunes) Description: Here comes a new challenger: it's the arcade simulation game you've been waiting for! Build your very own gaming... | Read more »

Price Scanner via

New App Reminds Us to Put Down Our Phones and...
Mode, a new smartphone app that makes us more mindful of how we use our devices, debuts in the app stores today. The Mode app tracks time spent in different modes of day-to-day life without... Read more
ZuumSpeed Personalized Speedometer + HUD For...
RMKapps has announced the release and immediate availability of ZuumSpeed 1.0, its personalized speedometer plus heads up display for iOS devices. ZuumSpeed gives users over 18 custom fonts available... Read more
Apple refurbished clearance 15-inch Retina Ma...
Apple has Certified Refurbished 2014 15″ 2.2GHz Retina MacBook Pros available for $1609, $390 off original MSRP. Apple’s one-year warranty is included, and shipping is free. They have refurbished 15... Read more
9-inch 128GB Silver iPad Pro on sale for $50...
B&H Photo has the 9.7″ 128GB Silver Apple iPad Pro on sale for $699 including free shipping plus NY tax only. Their price is $50 off MSRP. Read more
Why Use Indie Opera And Vivaldi Instead Of Sa...
For many years my web browser workhorses were various permutations and spinoffs of the Netscape/Mozilla/Firefox Open Source platform, and the Norwegian indie browser Opera, which I took a shine to... Read more
Western Digital Launches Worlds Fastest 256GB...
At the Mobile World Congress in Shanghai Western Digital Corporation this week introduced a new suite of 256 gigabyte (GB) microSD cards, which includes the new 256GB SanDisk Extreme microSDXC UHS-I... Read more
KeyCue 8.1 Integrates With Typinator To Displ...
Ergonis Software has released KeyCue 8.1, a new version of the company’s keyboard shortcut cheat sheet. KeyCue 8 introduced a new way to define a wide variety of triggers, which can be used to... Read more
Save up to $600 with Apple refurbished Mac Pr...
Apple has Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The following... Read more
21-inch 2.8GHz iMac on sale for $1199, save $...
Amazon has the 21″ 2.8GHz iMac (model #MK442LL/A) on sale for $1199.99 including free shipping. Their price is $100 off MSRP, and it’s the lowest price available for this model. Read more
13-inch 2.5GHz MacBook Pro (Apple refurbished...
Apple has Certified Refurbished 13″ 2.5GHz MacBook Pros available for $829, or $270 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros... Read more

Jobs Board

*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* Retail - Multiple Positions, Willow...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.