TweetFollow Us on Twitter

Engineering Tips
Volume Number:4
Issue Number:2
Column Tag:The Workstation Mac

Tips for Engineering Applications

By Paul Zarchan, Cambridge, Mass.

Introduction

With the advent of the Mac 2 and many third party Macintosh speed enhancers many engineers will now consider using the Macintosh for serious computation. Many of these engineers are currently using mainframe computers where the graphics environment is primitive or nonexistant and where CPU time is expensive and has little to do with turn around time. The purpose of this article is to give a few pointers in BASIC and FORTRAN, the languages with which engineers will initially feel most comfortable, on how to make effective use of the Macintosh for both graphics and speed.

Many engineers have heard that programming on the Mac is difficult and unlike mainframe programming. This is true if the end result is a commercial product. Making a program user friendly may cause simple code to grow by more than an order of magnitude. Using the various Macintosh toolbox routines requires the learning of a new language and a new way of thinking. However ordinary engineering applications are quite easy to program on the Mac - in fact even easier to program than on a mainframe or other micro - because of the user friendly environment, superior editing tools and virtually instantaneous feedback.

This article will show how engineers can modify ordinary programs, written in FORTRAN or BASIC, which generate numerical output and enhance these programs with the addition of a few lines of code so that they can serve as input drivers to professional commercial graphics software. In this way their numerical output can easily be converted to professional quality graphs and charts with little effort. They will discover, as I did, that instantaneous graphical feedback will not only help them convey their engineering message to others quickly but will also challenge them to modify their original program to get even more useful information. In addition, techniques for generating random numbers on the Mac will be discussed so that engineers can see how easy it is to perform monte carlo and statistical analysis. Finally, for those engineers wanting to run more complex problems on the Mac in BASIC, tips will be given on how to speed up program execution tiime with minimal changes to the program.

Plotting

The powerful graphic commands in MS BASIC and the access to the Macintosh toolbox in MacFortran permit the development of plotting packages in those respective languages. However, rather than re-inventing the wheel, it is better and much easier to use a very powerful commercial graphics package for engineers that already exists - Cricket Graph. The purpose of this section is to show the few lines of code are necessary to add to existing engineering programs so that the resultant output data,whether generated in BASIC or FORTRAN, can be transferred to Cricket Graph.

Cricket Graph requires it’s numerical input to be in a tab delimited format. Unfortuneately MS BASIC writes data to a file in comma delimited format. The simple fix to the problem is to have BASIC write it’s output to the screen for viewing purposes and to also write the output to the Macintosh clipboard for eventual pasting into Cricket Graph. Listing 1 presents a sample BASIC program which computes the expressions y=i2 and z=i3 for values of i ranging between 1 and 10. The resultant output is written to both the screen and clipboard.

OPEN “CLIP:”FOR OUTPUT AS #1
FOR I=1 TO 10
Y=I*I
Z=I^3
PRINT I,Y,Z
WRITE #1,I,Y,Z
NEXT I
CLOSE #1

Listing 1 - Writing Output to Clipboard in BASIC

The code in boldface can be added to any program so that output can be written to the clipboard in tab delimited format. The next step is to quit BASIC and then open Cricket Graph and finally to use the paste command to import the data. The resultant line plot, developed with Crickett Graph and slightly enhanced in MacDraw, is shown in Fig. 1.

Figure 1 - Using Cricket Graph to Plot BASIC Output

With Cricket Graph the ranges on the abscissa and ordinate can be changed quickly by double-clicking on the axis of interest. In addition, the BASIC data can be viewed in log-log form by simply choosing the log option in Cricket Graph. Grids can be added for additional readability. Figure 2 shows the same BASIC data viewed in gridded log-log format.

Figure 2 - BASIC Output Viewed in Log-Log Format

A FORTRAN program can also be modified so that its ouput can also be placed in a tabbed delimited format. This is easier to do in FORTRAN than in BASIC because it is possible to write data to a sequential file in tabbed delimited format. In order to illustrate the technique let’s consider the Fourier Series representation of the periodic square wave shown in Fig. 3.

Figure 3 - Fourier Series Representation of Periodic Square Wave

An infinite amount of terms would yield a perfect representation of the square wave whereas a finite number of terms would approximate the square wave. This effect is known as Gibbs phenomenon. Listing 2 presents a FORTRAN program which computes the first three terms of the periodic square wave Fourier Series and also writes the output to both the screen and also to a sequential file called “SAM”.

 REAL L
 CHARACTER*1 TAB
 TAB=Z’09'
 OPEN(1,STATUS=’NEW’,FILE=’SAM’)
 L=.5
 PI=3.14159
 C1=4./PI
 DO 10 X=0,1,.01
 F1=C1*SIN(PI*X/L)
 F3=F1+C1*SIN(3.*PI*X/L)/3.
 F5=F3+C1*SIN(5.*PI*X/L)/5.
 WRITE(9,*)X,F1,F3,F5
 WRITE(1,97)X,TAB,F1,TAB,F3,TAB,F5
 97FORMAT(F8.3,A1,F8.3,A1,F8.3,A1,F8.3)
 10CONTINUE
 CLOSE(1)
 PAUSE
 END

Listing 2 - Writing Tabbed Delimited Output to File in FORTRAN

The boldfaced statements in the above listing can be added to any FORTRAN program to write the output data, in a tabbed delimited format, to a sequential file. The sequential file can then be directly opened by Cricket Graph for plotting. For this example the resultant Cricket Graph output is displayed in line chart form in Fig. 4.

Figure 4 - FORTRAN Output Displayed in Cricket Graph

Random Numbers

Random numbers play an important role in engineering applications. They form the cornerstone of monte carlo and statistical analysis. In BASIC, uniformly distributed random numbers are available with the RND statement. Other random distributions can be constructed from the uniform distribution. For example, since the RND statement creates a uniformly distributed number between 0 and 1 with variance 1/12 and mean .5, a gaussian distributed random variable with variance 1 and zero mean can be constructed, according to the central limit theorem, by adding 12 uniformly distributed numbers together (12 times 1/12 is one) and subtracting 6. Therefore the following BASIC statement generates an approximate Gaussian distributed random variable with zero mean and unity standard deviation.

X=RND+RND+RND+RND+RND+RND+RND+RND+RND+RND+RND+RND-6

The distribution is approximately Gaussian since the maximum and minimum values of the distribution are ±6 rather than ±• . If the approximate Gaussian number generator is in a program inner loop and computer running time needs to be enhanced, fewer terms can be used in the above expression to speed up the program. For example, a six term approximate Gaussian number generator with unity variance and zero mean can be constructed from

X=1.414*(RND+RND+RND+RND+RND+RND-3)

In this case the maximum and minimum values of the approximate distribution are ±3 rather than ±• .

FORTRAN, unlike BASIC does not provide a uniform random number generator. However an efficient random number generator can be constructed in FORTRAN by making one toolbox call. TOOLBX(RANDOM) generates a uniformly distributed integer between ±32768 quickly. Listing 3 presents a FORTRAN program which, by using the above toolbox call, generates approximate gaussian random numbers and then puts the numbers into bins so that a probability density function can also be constructed.

 INTEGER BIN,RANDOM,SUM
 INTEGER*4 TOOLBX
 DIMENSION H(10000),X(10000)
 PARAMETER (RANDOM=Z’86140000')
 CHARACTER*1 TAB
 TAB=Z’09'
 OPEN(2,STATUS=’NEW’,FILE=’SAM’)
 XMAX=6.
 XMIN=-6.
 RANGE=XMAX-XMIN
 TMP=1/SQRT(6.28)
 N=1000
 BIN=50
 DO 10 I=1,N
 SUM=0
      DO 14 J=1,12
      IRAN=TOOLBX(RANDOM)
      SUM=SUM+IRAN
 14  CONTINUE
     X(I)=SUM/65536.
 10CONTINUE
 DO 20 I=1,BIN
 H(I)=0
 20CONTINUE
 DO 30 I=1,N
 K=INT(((X(I)-XMIN)/RANGE)*BIN)+.99
 IF( K<1)K=1
 IF(K>BIN)K=BIN
 H(K)=H(K)+1
 30CONTINUE
 DO 40 K=1,BIN
 PDF=(H(K)/N)*BIN/RANGE
 AB=XMIN+K*RANGE/BIN
 TH=TMP*EXP(-AB*AB/2.)
 WRITE(9,*)AB,PDF,TH
 WRITE(2,97)AB,TAB,PDF,TAB,TH
 97FORMAT(F8.3,A1,F8.3,A1,F8.3)
 40CONTINUE
 CLOSE(2)
 PAUSE
 END

Listing 3 - FORTRAN Program Illustrating Random Number Generation

The highlighted terms are those statements which are required by any FORTRAN program to generate uniformly distributed or gaussian distributed random numbers. Here X(I) is the resultant gaussian distributed number. In this particular program 1000 random numbers are calculated. The accuracy of the random number generator is illustrated by viewing the program output, shown in Fig. 5, which compares the sampled probability density function to the theoretical bell-shaped curve.

Figure 5 - FORTRAN Generates Gaussian Distributed Random Numbers Accurately

Speeding Up BASIC Programs

In a previous issue MacTutor issue1 it was shown how the transient response of a sixth order Butterworth filter could be simulated in FORTRAN using the second order Runge Kutta method for integrating the six differential equations. A block diagram of the Butterworth filter is repeated here for convenience in Fig. 6. Here the “1/s” terms represent integrations.

Figure 6 - Sixth Order Butterworth Filter

The resultant six first order differential equations, which can be obtained from Fig. 6, are:

A BASIC program which can integrate the above differential equations is shown in Listing 4.

DIM X(6),XOLD(6),XD(6)
START=TIMER
B1=3.86:B2=7.46:B3=9.13:B4=7.46:B5=3.86:B6=1:W0=50
XIN=1
ORDER=6
FOR I=1 TO ORDER
X(I)=0
NEXT I
T=0
H=.0005
S=0
BEGIN:
IF T>=.5 GOTO FINISH
S=S+H
FOR I=1 TO ORDER
XOLD(I)=X(I)
NEXT I
GOSUB INTEG
FOR I=1 TO ORDER
X(I)=X(I)+H*XD(I)
NEXT I
T=T+H
GOSUB INTEG
FOR I=1 TO ORDER
X(I)=.5*(XOLD(I)+X(I)+H*XD(I))
NEXT I
IF S>.004999 THEN
S=0
PRINT T,X(1)
END IF
GOTO BEGIN
FINISH:
PRINT TIMER-START
WHILE INKEY$=””:WEND
INTEG:
XD(1)=X(2)
XD(2)=X(3)
XD(3)=X(4)
XD(4)=X(5)
XD(5)=X(6)
XD(6)=(W0^6)*(XIN-B5*X(6)/(W0^5)-B4*X(5)/(W0^4)-B3*X(4)/(W0^3)-B2*X(3)/(W0^2)-B1*X(2)/W0-X(1))/B6
RETURN
END

Listing 4 - BASIC Simulation of Butterworth Filter

We can see from the listing that the integration step size, H, is .0005 sec. The running time for this program in interpretive MS BASIC is 229 sec on a Macintosh. Halving the step size or doubling the simulation time will double the running time. The program can be speeded up by using the MS BASIC Compiler and the resultant running time will decrease to 56 sec. Other methods can also be used to further enhance speed. For example the compiler and interpreter assume that all arrays are dynamic. However we can tell the compiler, but not the interpreter, that the arrays are static (as long as we aren’t going to redimension statements during the program) and significantly decrease the running times. In addition, making loop parameters integers, as is commonly done in FORTRAN, rather than default single precision real numbers will also enhance running time - especially with the compiler. Converting real numbers to integers can easily be accomplished in BASIC by adding a percent sign to the variable. Finally eliminating repeated calculations of constants from loops will also speed up the program. For example, the derivative XD(6) has many such constant computations which can easily be moved to the beginning of the program without destroying the readability of the code. The faster running BASIC program is shown in Listing 5.

DIM X(6),XOLD(6),XD(6)
START=TIMER
B1=3.86:B2=7.46:B3=9.13:B4=7.46:B5=3.86:B6=1:W0=50
XIN=1
ORDER%=6
W02=W0*W0
W03=W02*W0
W04=W03*W0
W05=W04*W0
W06=W05*W0
FOR I%=1 TO ORDER%
X(I%)=0
NEXT I%
T=0
H=.0005
S=0
BEGIN:
IF T>=.5 GOTO FINISH
S=S+H
FOR I%=1 TO ORDER%
XOLD(I%)=X(I%)
NEXT I%
GOSUB INTEG
FOR I%=1 TO ORDER%
X(I%)=X(I%)+H*XD(I%)
NEXT I%
T=T+H
GOSUB INTEG
FOR I%=1 TO ORDER%
X(I%)=.5*(XOLD(I%)+X(I%)+H*XD(I%))
NEXT I%
IF S>.004999 THEN
S=0
PRINT T,X(1)
END IF
GOTO BEGIN
FINISH:
PRINT TIMER-START
WHILE INKEY$=””:WEND
INTEG:
XD(1)=X(2)
XD(2)=X(3)
XD(3)=X(4)
XD(4)=X(5)
XD(5)=X(6)
XD(6)=W06*(XIN-B5*X(6)/W05-B4*X(5)/W04-B3*X(4)/W03-B2*X(3)/W02-B1*X(2)/W0-X(1))/B6
RETURN
END

Listing 6 - Faster BASIC Program

The terms that were changed to speed up the program are highlighted. Table 1 documents the speedup enhancements.

Condition Interpreter Compiler

Nominal 229 sec 56 sec

Make Arrays Static 229 sec 42 sec

Use Integers in Loops 211 sec 26 sec

Move Constant Computations 120 sec 22 sec

Out of Loops

Table 1 - Improving Speed of BASIC

We can see from Table 1 that there is a big payoff in using static arrays and integers when using the compiler. On the other hand, moving constant computations out of loops is more effective, in this case, when using the interpreter. For this example we can see that the net speed-up in being careful and using the compiler, rather than the interpreter, is more than a factor of 10 with only minor modifications to the original code. The best policy is to first get the programmed debugged and running using the interpreter because errors can be found and corrections can be made virtually instaneously. The tips for speed enhancement can then be applied when the program is checked out and is ready to be compiled.

References

1. Zarchan, P. “New Mac Workstation Potential”,

MacTutor, March 1987, pp. 15-21.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.