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

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

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

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

Thisallows example data for the program to be commented. The programming needed for the simple methodabove (using "!") is trivial, yet it saves time and effort by providing the necessary reminders about badmeasurements, troublesome calculations, people to be thanked, and other ideas.In our own programs, we try to save a copy of screen output in what we call a console image file. Thetactic is generally simple; we repeat every screen output command but direct the information to a file.

Thisfile may be set to NUL if no output is wanted. Clearly, this only works for sequential output. This is asevere hindrance if one wishes to design a program that uses pop-up menus and graphical interaction(mouse or pointer input). Fortunately, few scientific programs truly need such input/output. Moreover,it is much more demanding to program, so except where absolutely needed, we would recommend thesimpler approach.

This still allows one to provide menus and to output graphics, although a text-onlyconsole image file will have messages replacing graphics, or the names of files saving the graphic screens.The console image file can be incorporated directly into reports.Scripts of commands to programs avoid the risk that users type the wrong instructions. They show howto invoke a program’s features and can be edited to save effort and avoid mistakes.

In practice, such80Copyright © 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 Journalscripts, along with a console image file, are also vital to program development. Developers can automatea sequence of such tests (called "regression tests") to verify that new versions of software are free of "bugs"that have afflicted earlier editions.For UNIX and MS-DOS PCs, the operating system provides facilities for supplying scripts to programsvia input-output redirection. There are also operating system BATch command files within these operatingsystems. In graphical operating environments such as Microsoft Windows, OS/2 or the Macintosh Finder,one loses a good deal of this capability.

This may explain some of our diffidence concerning suchenvironments. We do not like the unproductive wait for (possibly slow) processes to finish. We prefer toprepare a set of commands for several tasks and let the machine do the work while we have coffee or dosomething else.A form of "batching" used in some programs allows users to see and select all or many options availablebefore execution begins, either using a point-and-click mechanism or menu selection.

Clearly, the valueof this approach will depend on the context of the computations at hand and the experience andknowledge of the users. Nevertheless, it is another method to reduce the amount of time users spendwaiting to provide the next piece of input data.All these tactics serve to document what the program does. They should, of course, be complemented byappropriate documentation, though we are tempted to agree with a dissatisfied user who returned apopular statistical package with the complaint "I don’t want it if I need to read the documentation to runit". One trend is to make "help" available within programs.

Another (Nash J C 1993b) is to have hypertextdocumentation as the framework from which software is operated. Separate paper documentation is likelyto diminish in popularity, in part because it rapidly becomes obsolete and cannot easily be corrected incase of errors.9.7Resilience to I/O Failure and Disk ProblemsIn the previous sections we wanted to avoid program failure caused by incorrect user action, e.g., byentering invalid data. Now we presume that the user behaves appropriately, but the computer systemitself suffers an "Unrecoverable Application Error (UAE)", i.e., fails. Such untoward events often concernperipheral devices — disks, printers, modems, instruments.

Some memory systems also have errorchecking (usually parity bit checking). Input/output handlers may perform various tests on the datareceived or sent to a peripheral. Parity checks are very common. So are extra bytes of redundantinformation sent each block of data that we can verify. Cyclic redundancy checks or check sums arealmost universally used for data transfer and storage.Errors detected via these techniques usually suggest a problem that cannot be fixed under the program’scontrol.

Still, we would like to have programs come to a controlled halt, as opposed to stopping or"hanging" so that only the reset button or power switch have any effect. Many collapses of ourcomputations are unavoidable. Others require an understanding of processes within the operating andlanguage software that are usually inaccessible to the programmer. When the application demands,however, we must wade into the manuals and work out actions to maintain control of our calculations.Some suggestions follow.•Disk or file out of space: Programs may try to write more data than files will hold because of a lackof physical space or operating system limits. Mechanisms resembling the disk directory facility(Section 5.3) may help find out space available.

Sometimes logical limitations may be overcome, butphysical constraints mean we must provide more storage capacity in some way. If we expect capacityshortages, then we could arrange that data is segmented across a set of files or storage units. Thesegments may later be combined if ways exist to store the combined file; special tools may be neededto do this.•Input/output device errors: To trap data transfer errors (e.g., parity) or control conditions (e.g., paperout) for peripherals, we will again need to interact with the operating system. Some compilers have9: DEBUGGING81special functions to allow detection of conditions within a program.•Output to files: To avoid direct control of peripherals, we could write all output to one or more files.Following successful completion of our program, we can COPY the output files to the relevantdevices.

This also saves paper when our program fails just before completion.•Suppression of user interrupts: For some applications, we wish to be sure that the "user" cannot carryout functions other than those intended. To do this, we must examine all input from the keyboard orpointer device and "trap" unwanted control commands. Sounds can be made to inform the user thatsuch input is invalid.In our experience, producing a code that carries out a desired calculation represents only 10% of thehuman effort needed to produce a fully functional, bug-free, piece of software with a friendly,documented interface and example data sets.

While "only 10%" may appear to devalue the role of theresearcher, we refer here to effort and perspiration rather than genius and inspiration.9.8Tests of Language TranslatorsPrevious sections of this chapter concern user error or hardware, generally peripheral, malfunction. Weturn now to programs through which the user may learn about the language processor or its interactionwith his/her system. That is, we will attempt to discover the properties of our computing machinery bymeans of programs that run on that machinery.

We have highlighted the topics below.Floating-point arithmetic: Several authors (Malcolm, 1972; Nash J C 1981b, 1981c, 1981h; Cody and Waite,1980; Karpinski, 1985) have suggested ways in which the floating-point arithmetic properties may in partbe discovered. We presume a model for each floating-point number in the form of n "digits"(Sign) (Exponent) (Radix point) Digit_1 Digit_2 . . .

Digit_nGenerally the most important pieces of information are the value of the radix (or base) of the arithmeticand the number of radix digits used (n). Prof. W. Kahan, in "A paranoid program to diagnosefloating-point arithmetic" (informally distributed), shows what can be done with imaginative programmingin BASIC to learn many features of the machine arithmetic used. Others have prepared PARANOIAprograms in C, FORTRAN, PASCAL and other languages (Karpinski, 1985).PARANOIA attempts to find out such information as:•The machine precision, eps, that is, the smallest positive real number such that1.0.

(Some authors use a slightly different definition.)(1.0 + eps) exceeds•The floating-point ceiling,•The floating-point floor, ffloor, that is, the smallest positive real number that can be stored and used.ceil, that is, the largest positive real number that can be stored and usedThe character set: It is possible in most language processors to convert an integer (in an appropriate range)into a character in the character set of the machine.

A simple loop over the allowed integers gives thecollating sequence of the characters, that is, the order into which characters are sorted. This is extremelyimportant for many applications such as name lists, indexes, catalogs etc. One fault of the ASCII characterset (ISO Standard 646, 1973) is that the upper and lower case letters are not in the usual "dictionary"collating sequence, so that sorting programs must be carefully devised to avoid placing "a" after "Z".For those of us who work in bilingual or multi-lingual environments, accented characters present furthercomplications. "Standard" character sets exist such as the IBM PC set, ISO sets, and those used by HewlettPackard and Apple, but the multiplicity of choices means we must be very careful in any situation wherewe must manipulate, search or sort data that use such characters.

We note that the correct display orprinting of accented upper case characters requires wide interline spacing. The lack of standardization istroublesome. Personally we prefer to drop the accents, but this may be undiplomatic.82Copyright © 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 JournalTo display or print characters, simple programs can be devised that fill a character variable withappropriate bits (i.e., a number). For example, in BASIC, we could use10203040FOR I=1 TO 127PRINT I;TAB(10);CHR$(I)NEXT ISTOPSimilarly, input characters may be altered because programmers of compilers or operating software havenot provided for them.

However, many peripheral devices such as printers and modems use specialcontrol characters to control special features, such as fonts or transmission speeds. One way to send suchcontrols is to enter them into a character string from the keyboard, a process thwarted if software masksor traps such characters. We can easily check this by running a program such as the following BASICcode.10203040DIM X$(2)INPUT "ENTER CHARACTER THEN (CR):",X$PRINT "CHARACTER NUMBER =",ASC(X$(1))GOTO 20Special functions: The logarithmic, power, exponential and trigonometric functions are a part of mostscientific computing languages.

They are unfortunately often very weakly programmed (Battiste, 1981).The user may carry out tests to protect against some errors that may occur, but the very large number ofpossible arguments for these functions usually precludes exhaustive checking. For example, anyrepresentable floating-point number could be an allowed input to the SIN function. Even if we restrictourselves to a reasonable range, the magnitude of the testing task is great.

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

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

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

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