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

Ride into the zombie apocalypse in style...
Back in the good old days of Flash games, there were a few staples; Happy Wheels, Stick RPG, and of course the apocalyptic driver Earn to Die. Fans of the running over zombies simulator can rejoice, as the sequel to the legendary game, Earn to Die... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Netflix Games expands its catalogue with...
It is a good time to be a Netflix subscriber this month. I presume there's a good show or two, but we are, of course, talking about their gaming service that seems to be picking up steam lately. May is adding five new titles, and there are some... | Read more »
Pokemon Go takes a step closer to real P...
When Pokemon Go was first announced, one of the best concepts of the whole thing was having your favourite Pokemon follow you in the real world and be able to interact with them. To be frank, the AR Snapshot tool could have done a lot more to help... | Read more »
Seven Knights Idle Adventure drafts in a...
Seven Knights Idle Adventure is opening up more stages, passing the 15k mark, and players may find themselves in need of more help to clear these higher stages. Well, the cavalry has arrived with the introduction of the Legendary Hero Iris, as... | Read more »
AFK Arena celebrates five years of 100 m...
Lilith Games is quite the behemoth when it comes to mobile games, with Rise of Kingdom and Dislyte firmly planting them as a bit name. Also up there is AFK Arena, which is celebrating a double whammy of its 5th anniversary, as well as blazing past... | Read more »
Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »

Price Scanner via MacPrices.net

Apple Studio Display with Standard Glass on s...
Best Buy has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Their price is the lowest available for a Studio Display among Apple’s retailers. Shipping is free... Read more
AirPods Max headphones back on sale for $449,...
Amazon has Apple AirPods Max headphones in stock and on sale for $100 off MSRP, only $449. The sale price is valid for all colors at the time of this post. Shipping is free: – AirPods Max: $449.99 $... Read more
Deal Alert! 13-inch M2 MacBook Airs on record...
Amazon has 13″ MacBook Airs with M2 CPUs in stock and on sale this week for only $829 in Space Gray, Silver, Starlight, and Midnight colors. Their price is $170 off Apple’s MSRP, and it’s the lowest... Read more
Apple Watch Ultra 2 on sale for $50 off MSRP
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose free... Read more
Apple introduces the new M4-powered 11-inch a...
Today, Apple revealed the new 2024 M4 iPad Pro series, boasting a surprisingly thin and light design that pushes the boundaries of portability and performance. Offered in silver and space black... Read more
Apple introduces the new 2024 11-inch and 13-...
Apple has unveiled the revamped 11-inch and brand-new 13-inch iPad Air models, upgraded with the M2 chip. Marking the first time it’s offered in two sizes, the 11-inch iPad Air retains its super-... Read more
Apple discontinues 9th-gen iPad, drops prices...
With today’s introduction of the new 2024 iPad Airs and iPad Pros, Apple has (finally) discontinued the older 9th-generation iPad with a home button. In response, they also dropped prices on 10th-... Read more
Apple AirPods on sale for record-low prices t...
Best Buy has Apple AirPods on sale for record-low prices today starting at only $79. Buy online and choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
13-inch M3 MacBook Airs on sale for $100 off...
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, along with Amazon’s, are the lowest currently available for new 13″... Read more
Amazon is offering a $100 discount on every 1...
Amazon has every configuration and color of Apple’s 13″ M3 MacBook Air on sale for $100 off MSRP, now starting at $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD): $999 $100 off... Read more

Jobs Board

*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
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-367184 **Updated:** Wed May 08 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Rehabilitation Technician - *Apple* Hill (O...
Rehabilitation Technician - Apple Hill (Outpatient Clinic) - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Read more
LPN-Physician Office Nurse - Orthopedics- *Ap...
LPN-Physician Office Nurse - Orthopedics- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Medical Assistant Lead - Orthopedics *Apple*...
Medical Assistant Lead - Orthopedics Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.