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

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

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

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

Others are called by location, that is, their address is passed to the subprogram, so we cannot avoid changing the values in such arguments if they are operated on within thesub-program.Several difficulties arise. Because arguments are usually defined by their positions, simple confusion inthe order of arguments in a call can have unexpected effects. Some arguments may define values forwhich we would like to use a constant. If the call is by location, we can actually change the values of a"constant".

We once changed the value of "3" to "10" by such an error. In C, the arguments of a functionare usually pushed onto a stack. This includes arrays, so that it is easy to overflow the available stackspace. We have experienced this type of difficulty in C, trying to translate FORTRAN code for the timingstudy of Chapter 18.We have already mentioned that BASIC assumes global variables and arrays.

This is also the case for the"languages" defined by several statistical and numerical packages. In other programming languages wemay wish to define global variables to simplify argument lists in calling sub-programs. In particular, itcan be extremely tedious to transfer all the data relating to a large problem via explicit reference in anargument list. We may also want to avoid the transfer of information about the computing environmentsuch as the machine precision, range limits and other "default" information.We think the main concern with the use of global variables is that both programmers and users mayforget that they are in play.

We believe that they should be used in simplifying programs, but that theymust be documented in the sub-program and preferably mentioned in the calling program. Otherwise we6: PROGRAMMING49can quickly find ourselves using global variables we believed were local.The FORTRAN construct of COMMON allows for global variables, but is best used in the labelledCOMMON form, so we can segment the global variables according to usage. This offers a convenientpartitioning of the data that is global to several routines.

For example, one block of common can bereserved for exogenous data, another for machine environment, another for working storage, etc.The transfer of data to a sub-program can also be accomplished by storing the data first in a structure(array, record, file, etc.) from which the sub-program can then extract it. C explicitly defines structures andpasses pointers to the structures rather than the structures themselves.This approach is straightforward to use, is very efficient of computer time, but may lead to errors if weare not careful to ensure both main and sub-program use exactly the same pointers and definitions.Files are another possible data transfer mechanism.

In particular for users with fast disks (or largepseudo-disks or RAM-disks), a reasonable choice for passing a large amount of information to asubroutine is to have the main program write a file and the subroutine read it again. Moreover, it offersthe potential for segmenting the execution of a program should we wish to check results, carry outanother task, or simply have some safeguards in case of error in later computations.Another type of subroutine call is that to a machine language routine. This is not a topic commonlyoffered in courses, yet it is important to many users of PCs who wish to interface calculations with datareceived from some unusual external or internal device.

One example is the job of controllingtemperatures in experimental equipment by turning on heaters or fans.Most PC language dialects offer methods for invoking machine code or linking to assembly languageroutines. However, the mechanisms can be complicated and are not for the faint of heart. Personally, wehave only carried out such operations via well-defined operations in BASIC (on 1970s vintage PCs) or byexecution of operating system calls from Turbo PASCAL on MS-DOS PCs.Typically, the major difficulty is that the program constructs for transfer of information require us to fillregisters or memory locations with data before we make the transfer of control. Similarly, after returnfrom the routine, we may have to unload data.

We resort to machine language calls only when there isno other way to accomplish the task, or where the advantages are too great to overlook. In such cases, werecommend keeping the calling mechanism as simple as possible.A special case is a call to execute another program. In PCs, it can be extremely useful to be able to launchone program from within another program. For example, in the middle of a data analysis, we may wantto invoke a text editor to allow us to alter the values of some numbers. To set the properties of a printerit may be useful to call up the operating system command shell to reset some parameters. The facilitiesfor making such transfers of control are provided in most programming languages. They arestraightforward to use, but we caution users to take note of all the details that must be accounted for.The different approaches to passing information to sub-programs are not equivalent in their demands oncomputing resources.

To underline this, see Figure 8.1.2, where different methods for calling sub-programswere used.6.6Programmer PracticesEvery programmer wants to program effectively. Where the target computer is a mainframe, theprogrammer may need to anticipate a range of inputs that could cause program failure. The PC user maybe prepared to suffer the occasional "crash." Indeed, practices designed to save our own time rather thanthat of the PC, or to "get the job done" may be higher priorities than an elegant source code. Therefore,our perception of efficient programming on a PC concerns the ease of use or ease of modification to a fargreater extent than the speed of execution.

This does not excuse, however, a lack of programmer50Copyright © 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 Journaldocumentation to show the state of development of a program code.We are ready to allow programs that are incomplete in the sense that they will not trap all invalid inputdata. A warning comment should be provided.

We are less comfortable with the use of nonstandardspecial features of a programming language or computer. Tricks that use "undocumented features" areequally unwelcome. This is simply because such enhancements cost many hours of work if we decide torun the program on another system, or even to modify it for another problem on the same PC.Programming is fun and a great learning experience — one of us (JN) enjoys it immensely — but it earnsthe scientific programmer and user no money, no credit for research done and no love from his or herboss. One must keep a proper perspective on the time and place for monkeying with the system. Aninformal cost-benefit analysis performed mentally has, at times, served us well and prevented monumentalwaste of time and effort.The main strategy that we recommend for effective programming is simplicity.

If you must use the fancyadvanced programming tools in a programming language, then at least describe what these do, so thatthe user who must implement the program on a PC without the particular feature can arrange to get thetask completed in more pedestrian fashion. Even better, replacement code can be provided in thecommentary or in documentation. In any event, the documentation should make note of any unusual orpossibly confusing structure.Previous Home Next7: SIZE DIFFICULTIES51Chapter 7Size Difficulties7.17.27.37.47.57.67.77.8Determining data storage limitsChoice or adjustment of data structuresUsage mapRestructuringReprogrammingChainingChange of methodData storage mechanisms for special matricesThis chapter deals with the situation where memory available to the user is not large enough to hold theprogram and data to solve a given problem. The proposed solutions change the program, though it maybe cheaper to physically increase the memory capacity.

For some PCs and operating systems, however,there have been address space limitations on the amount of memory that may be accessed at any givenmoment. Note that it may be possible to enlarge the memory available for programs by making temporaryor permanent configuration changes in the PC setup.7.1Determining Data Storage LimitsIf we have run out of space for our programs or data, we first need to know or find out what are the truelimits. The first limitation is on the physical memory — the total main memory installed in our PC. Theamount of main memory capacity is detected automatically by the start-up software of our system.Usually there is a test run to ensure memory integrity before loading the operating system, which has tokeep track of the memory since this is a key system resource it has to manage.The user memory is generally significantly smaller than the physical memory.

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

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

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

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