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

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 »
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 »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

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
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now 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.