c1-2 (Numerical Recipes in C)

PDF-файл c1-2 (Numerical Recipes in C) Цифровая обработка сигналов (ЦОС) (15311): Книга - 8 семестрc1-2 (Numerical Recipes in C) - PDF (15311) - СтудИзба2017-12-27СтудИзба

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

Файл "c1-2" внутри архива находится в папке "Numerical Recipes in C". PDF-файл из архива "Numerical Recipes in C", который расположен в категории "". Всё это находится в предмете "цифровая обработка сигналов (цос)" из 8 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "цифровая обработка сигналов" в общих файлах.

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

Текст из PDF

1.2 Some C Conventions for Scientific Computing15}(For additional calendrical algorithms, applicable to various historical calendars, see [8].)CITED REFERENCES AND FURTHER READING:Harbison, S.P., and Steele, G.L., Jr. 1991, C: A Reference Manual, 3rd ed. (Englewood Cliffs,NJ: Prentice-Hall).Kernighan, B.W. 1978, The Elements of Programming Style (New York: McGraw-Hill). [1]Yourdon, E. 1975, Techniques of Program Structure and Design (Englewood Cliffs, NJ: PrenticeHall).

[2]Jones, R., and Stewart, I. 1987, The Art of C Programming (New York: Springer-Verlag). [3]Hoare, C.A.R. 1981, Communications of the ACM, vol. 24, pp. 75–83.Wirth, N. 1983, Programming in Modula-2, 3rd ed. (New York: Springer-Verlag). [4]Stroustrup, B. 1986, The C++ Programming Language (Reading, MA: Addison-Wesley). [5]Borland International, Inc. 1989, Turbo Pascal 5.5 Object-Oriented Programming Guide (ScottsValley, CA: Borland International). [6]Meeus, J.

1982, Astronomical Formulae for Calculators, 2nd ed., revised and enlarged (Richmond, VA: Willmann-Bell). [7]Hatcher, D.A. 1984, Quarterly Journal of the Royal Astronomical Society, vol. 25, pp. 53–55; seealso op. cit. 1985, vol. 26, pp. 151–155, and 1986, vol. 27, pp. 506–507. [8]1.2 Some C Conventions for ScientificComputingThe C language was devised originally for systems programming work, not forscientific computing.

Relative to other high-level programming languages, C putsthe programmer “very close to the machine” in several respects. It is operator-rich,giving direct access to most capabilities of a machine-language instruction set. Ithas a large variety of intrinsic data types (short and long, signed and unsignedintegers; floating and double-precision reals; pointer types; etc.), and a concisesyntax for effecting conversions and indirections. It defines an arithmetic on pointers(addresses) that relates gracefully to array addressing and is highly compatible withthe index register structure of many computers.Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).if (julian >= IGREG) {Cross-over to Gregorian Calendar produces this correcjalpha=(long)(((float) (julian-1867216)-0.25)/36524.25);tion.ja=julian+1+jalpha-(long) (0.25*jalpha);} else if (julian < 0) {Make day number positive by adding integer number ofja=julian+36525*(1-julian/36525);Julian centuries, then subtract them off} elseat the end.ja=julian;jb=ja+1524;jc=(long)(6680.0+((float) (jb-2439870)-122.1)/365.25);jd=(long)(365*jc+(0.25*jc));je=(long)((jb-jd)/30.6001);*id=jb-jd-(long) (30.6001*je);*mm=je-1;if (*mm > 12) *mm -= 12;*iyyy=jc-4715;if (*mm > 2) --(*iyyy);if (*iyyy <= 0) --(*iyyy);if (julian < 0) iyyy -= 100*(1-julian/36525);16Chapter 1.PreliminariesFunction Prototypes and Header FilesANSI C allows functions to be defined with function prototypes, which specifythe type of each function parameter.

If a function declaration or definition witha prototype is visible, the compiler can check that a given function call invokesthe function with the correct argument types. All the routines printed in this bookare in ANSI C prototype form. For the benefit of readers with older “traditionalK&R” C compilers, the Numerical Recipes C Diskette includes two complete sets ofprograms, one in ANSI, the other in K&R.The easiest way to understand prototypes is by example. A function definitionthat would be written in traditional C asint g(x,y,z)int x,y;float z;becomes in ANSI CSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).Portability has always been another strong point of the C language.

C is theunderlying language of the UNIX operating system; both the language and theoperating system have by now been implemented on literally hundreds of differentcomputers. The language’s universality, portability, and flexibility have attractedincreasing numbers of scientists and engineers to it.

It is commonly used for thereal-time control of experimental hardware, often in spite of the fact that the standardUNIX kernel is less than ideal as an operating system for this purpose.The use of C for higher level scientific calculations such as data analysis,modeling, and floating-point numerical work has generally been slower in developing.In part this is due to the entrenched position of FORTRAN as the mother-tongue ofvirtually all scientists and engineers born before 1960, and most born after. Inpart, also, the slowness of C’s penetration into scientific computing has been due todeficiencies in the language that computer scientists have been (we think, stubbornly)slow to recognize. Examples are the lack of a good way to raise numbers to smallinteger powers, and the “implicit conversion of float to double” issue, discussedbelow.

Many, though not all, of these deficiencies are overcome in the ANSI CStandard. Some remaining deficiencies will undoubtedly disappear over time.Yet another inhibition to the mass conversion of scientists to the C cult has been,up to the time of writing, the decided lack of high-quality scientific or numericallibraries. That is the lacuna into which we thrust this edition of Numerical Recipes.We certainly do not claim to be a complete solution to the problem.

We do hopeto inspire further efforts, and to lay out by example a set of sensible, practicalconventions for scientific C programming.The need for programming conventions in C is very great. Far from the problemof overcoming constraints imposed by the language (our repeated experience withPascal), the problem in C is to choose the best and most natural techniques frommultiple opportunities — and then to use those techniques completely consistentlyfrom program to program.

In the rest of this section, we set out some of the issues,and describe the adopted conventions that are used in all of the routines in this book.1.2 Some C Conventions for Scientific Computing17int g(int x, int y, float z)int g(int, int, float);If a C program consists of multiple source files, the compiler cannot check theconsistency of each function call without some additional assistance.

The safestway to proceed is as follows:• Every external function should have a single prototype declaration in aheader (.h) file.• The source file with the definition (body) of the function should alsoinclude the header file so that the compiler can check that the prototypesin the declaration and the definition match.• Every source file that calls the function should include the appropriateheader (.h) file.• Optionally, a routine that calls a function can also include that function’sprototype declaration internally.

This is often useful when you aredeveloping a program, since it gives you a visible reminder (checked bythe compiler through the common .h file) of a function’s argument types.Later, after your program is debugged, you can go back and delete thesupernumary internal declarations.For the routines in this book, the header file containing all the prototypes is nr.h,listed in Appendix A. You should put the statement #include nr.h at the top ofevery source file that contains Numerical Recipes routines. Since, more frequentlythan not, you will want to include more than one Numerical Recipes routine in asingle source file, we have not printed this #include statement in front of thisbook’s individual program listings, but you should make sure that it is present inyour programs.As backup, and in accordance with the last item on the indented list above, wedeclare the function prototype of all Numerical Recipes routines that are called byother Numerical Recipes routines internally to the calling routine.

(That also makesour routines much more readable.) The only exception to this rule is that the smallnumber of utility routines that we use repeatedly (described below) are declared inthe additional header file nrutil.h, and the line #include nrutil.h is explicitlyprinted whenever it is needed.A final important point about the header file nr.h is that, as furnished onthe diskette, it contains both ANSI C and traditional K&R-style declarations. TheANSI forms are invoked if any of the following macros are defined: __STDC__,ANSI, or NRANSI. (The purpose of the last name is to give you an invocation thatdoes not conflict with other possible uses of the first two names.) If you have anANSI compiler, it is essential that you invoke it with one or more of these macrosSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).A function that has no parameters has the parameter type list void.A function declaration (as contrasted to a function definition) is used to“introduce” a function to a routine that is going to call it.

The calling routine needsto know the number and type of arguments and the type of the returned value. Ina function declaration, you are allowed to omit the parameter names. Thus thedeclaration for the above function is allowed to be written18Chapter 1.Preliminariesdefined. The typical means for doing so is to include a switch like “-DANSI” onthe compiler command line.Some further details about the file nr.h are given in Appendix A.Vectors and One-Dimensional Arraysfloat b[4],*bb;bb=b-1;The pointer bb now points one location before b.

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