Главная » Все файлы » Просмотр файлов из архивов » PDF-файлы » Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C

Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C, страница 7

PDF-файл Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C, страница 7 Численные методы (773): Книга - 6 семестрPress, Teukolsly, Vetterling, Flannery - Numerical Recipes in C: Численные методы - PDF, страница 7 (773) - СтудИзба2013-09-15СтудИзба

Описание файла

PDF-файл из архива "Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C", который расположен в категории "". Всё это находится в предмете "численные методы" из 6 семестр, которые можно найти в файловом архиве . Не смотря на прямую связь этого архива с , его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "численные методы и алгоритмы" в общих файлах.

Просмотр PDF-файла онлайн

Текст 7 страницы из PDF

Then program statements, like a[j+1]=b+c/3.0;. Here, the best programming advice is simply be clear, or (correspondingly) don’t be too tricky. Youmight momentarily be proud of yourself at writing the single linek=(2-j)*(1+3*j)/2;if you want to permute cyclically one of the values j = (0, 1, 2) into respectivelyk = (1, 2, 0). You will regret it later, however, when you try to understand thatline. Better, and likely also faster, isk=j+1;if (k == 3) k=0;Many programming stylists would even argue for the ploddingly literalswitch (j) {case 0: k=1; break;case 1: k=2; break;case 2: k=0; break;default: {fprintf(stderr,"unexpected value for j");exit(1);}}on the grounds that it is both clear and additionally safeguarded from wrong assumptions about the possible values of j. Our preference among the implementationsis for the middle one.In this simple example, we have in fact traversed several levels of hierarchy:Statements frequently come in “groups” or “blocks” which make sense only takenas a whole.

The middle fragment above is one example. Another isswap=a[j];a[j]=b[j];b[j]=swap;which makes immediate sense to any programmer as the exchange of two variables,whileans=sum=0.0;n=1;is very likely to be an initialization of variables prior to some iterative process. Thislevel of hierarchy in a program is usually evident to the eye.

It is good programmingpractice to put in comments at this level, e.g., “initialize” or “exchange variables.”The next level is that of control structures. These are things like the switchconstruction in the example above, for loops, and so on. This level is sufficientlyimportant, and relevant to the hierarchical level of the routines in this book, thatwe will come back to it just below.At still higher levels in the hierarchy, we have functions and modules, and thewhole “global” organization of the computational task to be done. In the musicalanalogy, we are now at the level of movements and complete works.

At these levels,1.1 Program Organization and Control Structures7modularization and encapsulation become important programming concepts, thegeneral idea being that program units should interact with one another only throughclearly defined and narrowly circumscribed interfaces. Good modularization practiceis an essential prerequisite to the success of large, complicated software projects,especially those employing the efforts of more than one programmer. It is also goodpractice (if not quite as essential) in the less massive programming tasks that anindividual scientist, or reader of this book, encounters.Some computer languages, such as Modula-2 and C++, promote good modularization with higher-level language constructs absent in C. In Modula-2, for example,functions, type definitions, and data structures can be encapsulated into “modules”that communicate through declared public interfaces and whose internal workingsare hidden from the rest of the program [4].

In the C++ language, the key conceptis “class,” a user-definable generalization of data type that provides for data hiding,automatic initialization of data, memory management, dynamic typing, and operatoroverloading (i.e., the user-definable extension of operators like + and * so as to beappropriate to operands in any particular class) [5]. Properly used in defining the datastructures that are passed between program units, classes can clarify and circumscribethese units’ public interfaces, reducing the chances of programming error and alsoallowing a considerable degree of compile-time and run-time error checking.Beyond modularization, though depending on it, lie the concepts of objectoriented programming. Here a programming language, such as C++ or Turbo Pascal5.5 [6], allows a module’s public interface to accept redefinitions of types or actions,and these redefinitions become shared all the way down through the module’shierarchy (so-called polymorphism).

For example, a routine written to invert amatrix of real numbers could — dynamically, at run time — be made able to handlecomplex numbers by overloading complex data types and corresponding definitionsof the arithmetic operations. Additional concepts of inheritance (the ability to definea data type that “inherits” all the structure of another type, plus additional structureof its own), and object extensibility (the ability to add functionality to a modulewithout access to its source code, e.g., at run time), also come into play.We have not attempted to modularize, or make objects out of, the routines inthis book, for at least two reasons.

First, the chosen language, C, does not really makethis possible. Second, we envision that you, the reader, might want to incorporatethe algorithms in this book, a few at a time, into modules or objects with a structureof your own choosing. There does not exist, at present, a standard or accepted setof “classes” for scientific object-oriented computing. While we might have tried toinvent such a set, doing so would have inevitably tied the algorithmic content of thebook (which is its raison d’être) to some rather specific, and perhaps haphazard, setof choices regarding class definitions.On the other hand, we are not unfriendly to the goals of modular and objectoriented programming.

Within the limits of C, we have therefore tried to structureour programs to be “object friendly.” That is one reason we have adopted ANSIC with its function prototyping as our default C dialect (see §1.2). Also, withinour implementation sections, we have paid particular attention to the practices ofstructured programming, as we now discuss.8Chapter 1.PreliminariesControl StructuresAn executing program unfolds in time, but not strictly in the linear order inwhich the statements are written. Program statements that affect the order in whichstatements are executed, or that affect whether statements are executed, are calledcontrol statements. Control statements never make useful sense by themselves. Theymake sense only in the context of the groups or blocks of statements that they in turncontrol.

If you think of those blocks as paragraphs containing sentences, then thecontrol statements are perhaps best thought of as the indentation of the paragraphand the punctuation between the sentences, not the words within the sentences.We can now say what the goal of structured programming is. It is to makeprogram control manifestly apparent in the visual presentation of the program. Yousee that this goal has nothing at all to do with how the computer sees the program.As already remarked, computers don’t care whether you use structured programmingor not. Human readers, however, do care. You yourself will also care, once youdiscover how much easier it is to perfect and debug a well-structured program thanone whose control structure is obscure.You accomplish the goals of structured programming in two complementaryways.

First, you acquaint yourself with the small number of essential controlstructures that occur over and over again in programming, and that are thereforegiven convenient representations in most programming languages. You should learnto think about your programming tasks, insofar as possible, exclusively in terms ofthese standard control structures. In writing programs, you should get into the habitof representing these standard control structures in consistent, conventional ways.“Doesn’t this inhibit creativity?” our students sometimes ask. Yes, justas Mozart’s creativity was inhibited by the sonata form, or Shakespeare’s by themetrical requirements of the sonnet. The point is that creativity, when it is meant tocommunicate, does well under the inhibitions of appropriate restrictions on format.Second, you avoid, insofar as possible, control statements whose controlledblocks or objects are difficult to discern at a glance. This means, in practice, that youmust try to avoid named labels on statements and goto’s.

It is not the goto’s thatare dangerous (although they do interrupt one’s reading of a program); the namedstatement labels are the hazard. In fact, whenever you encounter a named statementlabel while reading a program, you will soon become conditioned to get a sinkingfeeling in the pit of your stomach. Why? Because the following questions will, byhabit, immediately spring to mind: Where did control come from in a branch to thislabel? It could be anywhere in the routine! What circumstances resulted in a branchto this label? They could be anything! Certainty becomes uncertainty, understandingdissolves into a morass of possibilities.Some examples are now in order to make these considerations more concrete(see Figure 1.1.1).Catalog of Standard StructuresIteration.In C, simple iteration is performed with a for loop, for examplefor (j=2;j<=1000;j++) {b[j]=a[j-1];a[j-1]=j;}91.1 Program Organization and Control Structuresiterationcomplete?noblockyeswhileconditionfalsetrueblockincrementindexFOR iteration(a)WHILE iteration(b)blockblockbreakconditiontruewhileconditiontruefalseblockfalseDO WHILE iteration(c)BREAK iteration(d)Figure 1.1.1.

Standard control structures used in structured programming: (a) for iteration; (b) whileiteration; (c) do while iteration; (d) break iteration; (e) if structure; (f) switch structure10Chapter 1.ifconditionfalseelse ifconditionelse ifcondition...truetrueblockfalsePreliminariesfalsetrueblockblockelse block...IF structure(e)switchexpressioncasematch?yesblocknobreak?yesnocasematch?yesblocknoyesbreak?nodefault blockSWITCH structure(f )Figure 1.1.1. Standard control structures used in structured programming (see caption on previous page).1.1 Program Organization and Control Structures11Notice how we always indent the block of code that is acted upon by the controlstructure, leaving the structure itself unindented.

Notice also our habit of putting theinitial curly brace on the same line as the for statement, instead of on the next line.This saves a full line of white space, and our publisher loves us for it.IF structure. This structure in C is similar to that found in Pascal, Algol,FORTRAN and other languages, and typically looks likeif (...) {...}else if (...) {...}else {...}Since compound-statement curly braces are required only when there is morethan one statement in a block, however, C’s if construction can be somewhat lessexplicit than the corresponding structure in FORTRAN or Pascal.

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