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

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
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 »

Price Scanner via MacPrices.net

Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
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

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.