Главная » Просмотр файлов » Nash - Scientific Computing with PCs

Nash - Scientific Computing with PCs (523165), страница 26

Файл №523165 Nash - Scientific Computing with PCs (Nash - Scientific Computing with PCs) 26 страницаNash - Scientific Computing with PCs (523165) страница 262013-09-15СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 26)

According to Grace Hopper, "things were going badlywrong in one of the circuits of the long, glass-enclosed computer. Finally, someone located the troublespot, and using ordinary tweezers, removed the problem, a two-inch moth. From then on, when anythingwent wrong with a computer, we said it had bugs in it." (SIAM News, 1992) "Debugging" has sincebecome the accepted name for the process of correcting the faults in a program so that it runs as desired.In this chapter we shall consider how the user may best carry out this step, whether in a traditionalprogram, in a command script for an application package or within the application program itself.Debugging skill cannot make up for poor program design and implementation, but errors are a part ofall programs at various times in their life-cycle. It is important to have a strategy for finding andcorrecting them.The chapter also considers software testing and validation, that is, the steps that go beyond merelysatisfying ourselves there are no obvious errors.

We want reliable performance in a variety of situationsfor an array of problems.9.1Using Output WiselyThe first step in removing errors is to find their cause(s). The cause may be quite distant from theresultant effect, both in execution time and lines of program code. To find the "bug", we must make theprogram tell us what is, and has been, going on by inserting commands to display or print informationabout the state of our computation. Eventually, when the program works perfectly, the intermediateoutput is a nuisance.A useful tactic is a switch mechanism in the program so that intermediate output may be suppressed.Commonly a program variable provides the switch; if zero/non-zero, it permits/inhibits the executionof output commands.

Some compilers allow us to leave out statements at compile time by means ofcompiler switches. Then there is no runtime overhead, though we do have to recompile the program.Another choice is to direct diagnostic output only to a screen so that it is not saved. We could also sendit to a separate file, possibly on a RAM-disk. In either case writing to screens or files takes time.

Note thatthe time to write to video memory is usually much slower than to regular memory. Table 9.1.1 showsregular and video memory write timings for three MS-DOS PCs.If intermediate output is produced, it is obvious that it should contain sufficient information to enable theerror to be found. The important pieces of information that must be transmitted are:74Copyright © 1984, 1994 J C & M M NashSCIENTIFIC COMPUTING WITH PCsNash Information Services Inc., 1975 Bel Air Drive, Ottawa, ON K2C 0X1 CanadaCopy for:Dr. Dobb’s Journal•The path taken through the program, so we can learn which program instructions were executed andin which order;•The values of control variables such as arguments in logical expressions, looping variables, and flagvariables;•Values of selected result variables that indicate successful completion of various parts of the program.We would add to this a requirement that all listings should have a time and date stamp.

Mostcomputational analyses require multiple "runs," so that a time/date for each is a minimal point ofreference. Some software allows the user to provide titles or comments. However, we would value thisless than the time stamp since users are notoriously lazy when it comes to providing meaningfulcommentary to individual computations.Simply "turning on the debug switch" will seldom give enough information to allow an error to becorrected. One often has to insert additional output statements to find a specific error, especially if thedifficulty involves an interaction between the program, data and computing system.

Many systems limitline length for output, so a program may run satisfactorily for many months before particular input datacauses it to split numbers across two lines, destroying the appearance of the results. Users may presentleast squares fitting programs with collinear data for which most are not designed. We have had troubleseveral times (e.g., in Nash J C, 1992). These limitations should, of course, be recognized during the designphase of program development and reported clearly to the user. Instead, tedious analysis of program flowand data are usually needed.We now present an example of finding bugs by use of selected output.

Suppose we wish to find theminimum of a function f(x) of one variable, x, by using a quadratic approximation to the function. Atthree values x=A,B,C, we have f(A), f(B), and f(C), and can fit a parabola (that is, a quadraticapproximation) to the points (A, f(A)), (B, f(B)), and (C, f(C)). A partial program to do this is givenin Figure 9.1.1.To use this approximation inside a program that finds the minimal argument x_min and minimal valuef(x_min) for f(x), we would now have to find the minimum of the parabola, that is, by setting thederivative of the approximating function(9.1.1)g(x) = A + B x + C x2to zero.(9.1.2)g’(x) = B + 2 C x = 0so that our trial minimal argument is(9.1.3)xtrial = -B / (2 C)For certain functions and/or sets of points, this estimate xtrial of the minimum may actually be near amaximum.

The program, as written, does not check for this possibility. We can quite easily plot the pointsto see that they form a concave triple. If A < B < C we would like f(B) to be less than (see overleaf)Table 9.1.1 Comparing regular and video memory write times (microseconds) using ATPERF (PC TechJournal AT Hardware Performance Test,Version 2.00, Copyright (c) 1986, 1987, ZiffCommunications Co.,Written by Ted Forgeron and Paul Pierce). Note that the 386 andNOTEBOOK machines are nominally equivalent in processor and speed.386Average RAM write time: 0.07Average Video write time: 1.36NOTEBOOK0.122.642860.253.119: DEBUGGING(9.1.4)75f(A) + (B - A) * (f(C) - f(A)) / (C - A)This last value is the linear interpolant between the pointsgives the program after appropriate modification.9.2(A, f(A)) and (C, f(C)) at x=B. Figure 9.1.2Built-in Debugging ToolsSome language processors have built-in trace and debug options.

These can be very useful in well-trainedhands. Unfortunately, we have found few that are easy to use because of the learning cost and the volumeof output produced.The benefits that trace and debug options may bring, depending on implementation, are:•Automatic output of all variables, or else of user-selected variables;•Record of program flow;•Single statement execution so that the user may execute the program one statement at a time;•Array dimension checking;•Checking for undefined variables or array elements.The big disadvantage lies in the effort to learn how to use them. If one is using several differentcomputational tools, it is easier to use printouts of a few key variables, which can be a trivial task whenthe language processor is an interpreter, e.g., MATLAB, Stata, and many BASICs.

We may even be able todisplay variable contents while execution is stopped. Compilers require slightly more tedious steps to betaken, in that the program source code must be altered and then recompiled, linked and loaded. However,much of the tedium can be overcome, either by working within a suitable program developmentenvironment such as Borland’s Turbo Pascal Integrated Development Environment, by using a macroeditor that provides similar features, e.g., BRIEF, or by using BATch command scripts or similarFigure 9.1.1Partially completed program to find the minimum of a function of one variable byquadratic approximation.Note that a quadratic function (line 510) is used to test that the formulas were correctly implemented.This example does not include steps to ensure stability of the computation of the approximatingparabola, and for the three abscissa x = -1, 0, +1, an incorrect approximation results.10 PRINT "QUADRATIC APPROXIMATION TO A FUNCTION MINIMUM"15 DIM X(3),Y(3)20 REM SUBROUTINE AT LINE 500 PUTS F(Z) IN F30 PRINT "INPUT 3 ARGUMENTS OF FUNCTION"40 INPUT X(1),X(2),X(3)50 FOR I=1 TO 360 LET Z=X(I) : GOSUB 50062 PRINT " F(";Z;")=";F70 LET Y(I)=F80 NEXT I300 REM QUADRATIC APPROXIMATION310 REM DENOMINATOR FOR COEFF 1 OF PARABOLA320 LET K4=(X(1)-X(2))*(X(2)-X(3))*(X(1)-X(3))330 REM COEFF 1340 LET C=((Y(1)-Y(2))*(X(2)-X(3))-(Y(2)-Y(3))*(X(1)-X(2)))/K4350 REM COEFF 2360 LET B=(Y(1)-Y(2))/(X(1)-X(2))-C*(X(1)+X(2))370 REM THIRD COEFF380 LET A=Y(1)-X(1)*(C*X(1)+B)390 PRINT "PARABOLA IS ";A;"+ (";B;400 PRINT ")*X+(";C;")*X^2"410 LET Z=-B*0.5/C420 GOSUB 500430 PRINT "FN VALUE=";F;" AT ";Z440 STOP500 REM FN510 LET F=(Z*Z-4)*Z^4: REM QUARTIC TEST FUNCTION520 RETURN76Copyright © 1984, 1994 J C & M M NashNash Information Services Inc., 1975 Bel Air Drive, Ottawa, ON K2C 0X1 CanadaSCIENTIFIC COMPUTING WITH PCsCopy for:Dr.

Dobb’s Journaltools. The goal is to avoid many keystrokes. We confess to largely ignoring the debugging tools built intothe programming environments we use because of learning cost.We should not forget the error reporting that is always a part of any language processor or package. Itis an unfortunate reality that the error reporting may be limited to one of a few very cryptic messages.We consider error reports that list only an error number to be unacceptable. Fortunately, most suchunfriendly products are now obsolete.Figure 9.1.2Partially completed program to find the minimum of a function of one variable byquadratic approximation.This version incorporates a test for the proper arrangement of the three points used to calculate theapproximating parabola.

Note that several other changes would be needed to make this a reliableprogram. (See for example, Nash, 1990d, Algorithm 17. In the first edition of this book there is atypographical error in step 15, which should read "goto step 18" instead of "goto step 20".)10 PRINT "QUADRATIC APPROXIMATION TO FUNCTION MINIMUM"15 DIM X(3),Y(3)20 REM SUBROUTINE AT 500 PUTS F(Z) IN F30 PRINT "INPUT 3 ARGUMENTS OF FUNCTION"40 INPUT X(1),X(2),X(3)50 FOR I=1 TO 360 LET Z=X(I) : GOSUB 50062 PRINT " F(";Z;")=";F70 LET Y(I)=F80 NEXT I90 REM AT THIS POINT TEST VALUES100 FOR I=1 TO 2 : REM BEGIN BY ORDERING THE ARGUMENTS110 FOR J=1+I TO 3120 IF X(I)<X(J) THEN 180130 IF X(I)=X(J) THEN STOP : REM EQUAL ARGUMENTS CAUSE135 REM FAILURE IN CALCULATION OF APPROXIMATING PARABOLA140 LET T=X(I):LET X(I)=X(J):LET X(J)=T150 LET T=Y(I):LET Y(I)=Y(J):LET Y(J)=T180 NEXT J190 NEXT I200 LET Y2=(X(2)-X(1))*(Y(3)-Y(1))/(X(3)-X(1))+Y(1)205 REM Y2 IS LINEAR APPROXIMATION TO Y(2) FROM Y(1),Y(3)210 IF Y2>Y(2) THEN 300220 PRINT "POINTS OUT OF ORDER; ENTER NEW C=";230 INPUT X(3)260 GOTO 50300 REM QUADRATIC APPROXIMATION310 REM DENOMINATOR FOR COEFF 1 OF PARABOLA320 LET K4=(X(1)-X(2))*(X(2)-X(3))*(X(1)-X(3))330 REM COEFF 1340 LET C=((Y(1)-Y(2))*(X(2)-X(3))-(Y(2)-Y(3))*(X(1)-X(2)))/K4350 REM COEFF 2360 LET B=(Y(1)-Y(2))/(X(1)-X(2))-C*(X(1)+X(2))370 REM THIRD COEFF380 LET A=Y(1)-X(1)*(C*X(1)+B)390 PRINT "PARABOLA IS ";A;"+ (";B;400 PRINT ")*X+(";C;")*X^2"410 LET Z=-B*.5/C420 GOSUB 500430 PRINT "FN VALUE=";F;" AT ";Z440 STOP500 REM FN510 LET F=(Z*Z-4)*Z^4515 REM LET F=1+Z*(2+3*Z) : REM TEST FUNCTION (PARABOLA)520 RETURN9.3Listings and Listing ToolsAs mentioned in Section 5.4, a crude but often effective backup mechanism is a hard copy listing of filecontents.

Характеристики

Тип файла
PDF-файл
Размер
1,45 Mb
Тип материала
Учебное заведение
Неизвестно

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6264
Авторов
на СтудИзбе
316
Средний доход
с одного платного файла
Обучение Подробнее