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

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

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

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

Thusthe run time to compute a solution may be important. If we have to compile programs, the compile andlinkage time may be important. The amount of time and effort the user or programmer need to implementand install a working program is another measure of efficiency. The acquisition or license costs of anyprograms must be totalled. This may be exchanged for user time and effort if we write our own codes.Availability of freeware programs is a factor to consider here. A last, but extremely important, measureof efficiency is user happiness; while difficult to measure, user attitudes to an algorithm color effectiveuse of it. These attitudes should be considered when choosing an algorithm for a particular task.12.3 Algorithm Implementation - ProgrammingFor most problems, we will estimate linear models in an application program and never need to program,but we will continue our example as if it were a less common task.

This section concerns traditionalprogramming rather than the writing of scripts for packages. The programming step in solving anumerical problem is straightforward if the method and algorithm are clearly stated and well understood,but ambiguities and unstated conditions must be clarified and resolved, and errors avoided.Step one is to decide the programming language(s) to be used. This depends on the programming toolsavailable, the language features needed, our ability to use the tools, and our preferences.

Specialconditions may alter our choice. For example, if we must solve problems in a microprocessor-basedcontroller, we need a language that can be compiled to the appropriate machine code. If we wantportability across computing platforms, we must choose a language for which standardized compilers existon all target machines.Whatever language is available, we want to avoid over-sophisticated coding, the use of special languagedialects or undocumented features, or inclusion of unverified source code in our final program. Someexamples of such poor practices follow.12: STEPS IN PROBLEM SOLVING107To save program length, programming tricks may be used that accomplish several algorithmic tasks atonce.

At times such techniques can be useful, but they complicate our work and can cause grief whendebugging. Programs that rely on the system (hardware or software) to initialize variables or seedpseudo-random number sequences save us the code and memory needed to perform the initialization butmay give unpredictable results with any change in the system configuration or a move to anothercomputer.

The use of constructs likeDIMENSION A(1)in FORTRAN to permit variable dimensioning of arrays, while used in early programs, should be avoided.The use of single subscripts for two dimensional arrays as in the early IBM System/360 ScientificSubroutine Package (Manual 360-CM-03X) had the same goal, but is notorious for its preoccupation withsaving index calculation time. The resulting codes are difficult to follow and alter. Similarly, the brilliantand tiny Bauer-Reinsch (1971) Gauss-Jordan inversion of a positive definite symmetric matrix is difficultto follow and understand (Nash, J C, 1990d, Chapter 8).Programmers may also use tricks to access data via pointers.

We urge directness and simplicity. OlderFORTRAN programs sometimes used EQUIVALENCE to access data in some unusual way. For example,data read in by an A4 format to a single-precision array could be used 8 characters at a time via a doubleprecision array EQUIVALENCED to the same location. This fails if the single and double precision datatypes do not match up perfectly. An example on Page 1 of Kernighan and Plauger (1974) shows how notto set a matrix to the identity.If it is imperative that we use programming constructs that support special features of a particularcomputer, we should identify non-standard program code to make modification for other compilers ormachines easier.

We may be the ones to make the changes.We should proof-read a program at some point to see that it makes sense, even if test results seem correct.There are still possibilities for grave errors due to paths through the program that the test cases do notexercise. See Kernighan and Plauger (1974) for a short, readable, and valuable guide to reasonableprogramming style.When programming, we want to avoid being diverted from the task of finding an adequate solution forthe real problem in the search for a perfect method for the mathematical one. Remember the original task!We are confirmed (and somewhat unrepentant) sinners in this regard, since it is very satisfying to finda better, faster or more accurate methods for a particular problem. For academics, there are articles innumerical analysis or computing journals, the opportunity to show off programming virtuosity tocolleagues and the inner warmth of cracking a challenging puzzle.

However, unless the new method haswide production use, the solution of the real problem is the one that buys the groceries.12.4 DocumentationDocumentation is a permanent headache in all spheres of programming. Ideally, the documentation existsbefore the program is written. This is possible to the extent that the algorithm is expressed in detail insome pseudo-code such as a step-and-description form. What must be added is information on the orderand format of data that is needed for a successful computation. This information must also be kept currentas the program is applied to new problems or moved to different computers.The main reason documentation is forever incomplete, out of date or contains errors, is that documentingtoday’s work only helps us tomorrow, while the rewards or brickbats are earned for results now, sowriting documentation is easily postponed.

The only remedy is continuous discipline and goodprogramming habits, but no programmer maintains a perfect record in this regard.Some workers like to have all their documentation stored in the computer, as comments within theprogram or in a text or hypertext file that can be called up by the program.

We must still ensure that the108Copyright © 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 Journalcomments are correct and up to date. In interpretive environments, comments may also slow down theexecution of the program.The importance of documentation is to clarify information that is not obvious from the program code.Thus, comments of the form100 FOR I = 1 TO N: REM LOOP ON Iare a waste of time, whereas100 FOR I = I TO N: REM LOOP OVER ALL PRODUCT CODEStells the reader something about the use of the program code.Full documentation should describe the following aspects of a program:•How the program is invoked, that is, a step-by-step set of instructions to using it;•A data dictionary (Section 6.2) describing the function of each variable array, string or other datastructure in the program;•The author of the program, date of writing or date of last alteration;•The files used by the program, their size, type and format;•Any special requirements and all devices used by the program.

For example, the program may assumea 24 X 80 video output format, a 120 character per line printer or clock accessible via some I/O port.•Any non-standard or unusual programming language constructs;•The mechanisms used in any of the algorithm steps, or a reference to sources where this informationmay be found.Despite all the above, documentation should be as succinct as possible. To this end, summary cards arevery useful, containing all the information needed to operate the program in a small, portable reference.12.5 Testing — Data EntryThe first level at which a program may fail is where the user must enter data into the program. Forexample, let us consider the entry of the order of a square matrix, which must not be bigger than 50 X50, its maximum dimensions.

This number will be an integer. Consider the following examples, where [cr]denotes the "carriage return", (ASCII 13, OD Hex):4[cr]65[cr][cr]A[cr]4J[cr]4,5[cr] 4.5[cr]Only the first entry is acceptable. The second is too large for the maximum dimensions of the matrix. Thethird is null, and some programs may take the entry to be zero, especially if the carriage return ispreceded by blanks. The fourth entry is the letter A, the fifth has a letter J after a number.

The sixth iseither wrong in having a comma or uses the European form for the decimal point and, like the finalexample, is not an integer.Catering to the needs of users who may employ either commas or periods for decimal points may be quitedifficult. We may have to read numbers as character strings that are then converted to numerical valuesunder control of our program, rather than use the operating system or language processor (Section 9.5).It is unfortunate that truly robust programs require such drastic steps. The input handlers associated withthe operating system, programming environment, linkage or run-time libraries or packaged computingenvironments are rarely documented enough that we can know in advance which error conditions theywill detect.

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

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

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

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