Главная » Просмотр файлов » Morgan - Numerical Methods

Morgan - Numerical Methods (523161), страница 15

Файл №523161 Morgan - Numerical Methods (Morgan - Numerical Methods) 15 страницаMorgan - Numerical Methods (523161) страница 152013-09-15СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Suchfractions are often used within the set of natural numbers to represent the result ofsuch an operation. Because this fraction is a symbol, it can represent any value, nomatter how irrational or abstruse.A real number offers another kind of fraction, one that expands the number linewith negative powers of the base you’re working with. Base 10, involves a decimalexpansion such that a-1, * 10-l0 + a-2* 10-10+ a-3 * 10-10. Nearly all scientific,mathematical, and everyday work is done with real numbers because of theirprecision (number of representable digits) and ease of use.The symbolic fraction 1/3 exactly represents the division of one by three, but afractional expansion in any particular base may not, For instance, the symbolicfraction l/3 is irrational in bases 10 and 2 and can only be approximated by.33333333D and .55555555H.A value in any base can be irrational-that is, you may not be able to representit perfectly within the base you’re using.

This is because the positional numberingsystem we use is modular, which means that for a base to represent a symbolicfraction rationally all the primes of the denominator must divide that base evenly.It’s not the value that’s irrational; it’s just that the terms we wish to use cannot expressit exactly. The example given in the previous paragraph, l/3, is irrational in base 10but is perfectly rational in base 60.There have been disputes over which base is best for a number system. Thedecimal system is the most common, and computers must deal with such numbersat some level in any program that performs arithmetic calculations. Unfortunately,most microprocessors are base 2 rather than base 10.

We can easily represent decimal85NextNUMERICAL METHODSintegers, or whole numbers, by adding increasingly larger powers of two. Decimalfractions, on the other hand, can only be approximated using increasingly largernegative powers of two, which means smaller and smaller pieces. If a fraction isn’texactly equal to the sum of the negative powers of two in the word size or data typeavailable, your representation will only be approximate (and in error). Since we havelittle choice but to deal with decimal reals in base 2, we need to know what that meansin terms of the word size required to do arithmetic and maintain accuracy.The focus of this chapter is fixed-point arithmetic in general and fractional fixedpoint in particular.Fixed PointEmbedded systems programmers are often confronted with the task of writingthe fastest possible code for real-time operation while keeping code size as small aspossible for economy.

In these and other situations, they turn to integer and fixedpoint arithmetic.Fixed point is the easiest-to-use and most common form of arithmetic performedon the microcomputer. It requires very little in the way of protocol and is thereforefast-a great deal faster than floating point, which must use the same functions asfixed point but with the added overhead involved in converting the fixed-pointnumber into the proper format. Floating point is fixed point, with an exponent forplacing the radix and a sign. In fact, within the data types defined for the two standardforms of floating-point numbers, the long real and short real, fewer significant bitsare available than if the same data types were dedicated to fixed-point numbers.

Inother words, no more precision is available in a floating-point number than in fixedpoint.In embedded applications, fixed point is often a must, especially if the systemcan not afford or support a math coprocessor. Applications such as servo systems,graphics, and measurement, where values are computed on the fly, simply can’t waitfor floating point to return a value when updating a Proportional-Integral-Derivative(PID) control loop such as might be used in a servo system or with animated graphics.So why not always use integer or fixed-point arithmetic?Probably the most important reason is range. The short real has a decimal rangeof approximately 1038 to 10-38 (this is a range, and does not reflect resolution or86REAL NUMBERSaccuracy; as you’ll see in the next chapter, floating-point numbers have a realproblem with granularity and significance).

To perform fixed-point arithmetic withthis range, you would need 256 bits in your data type, or 32 bytes for each operand.Another reason is convenience. Floating-point packages maintain the positionof the radix point, while in fixed point you must do it yourself.Still another reason to use floating-point arithmetic is the coprocessor. Using acoprocessor can make floating point as fast as or faster than fixed point in manyapplications.The list goes on and on.

I know of projects in which the host computercommunicated with satellites using the IEEE 754 format, even though the satellitehad no coprocessor and did not use floating point. There will always be reasons touse floating point and reasons to use fixed point.Every application is different, but if you’re working on a numerically intensiveapplication that requires fast operation or whose code size is limited, and your systemdoesn’t include or guarantee a math coprocessor, you may need to use some form offixed-point arithmetic.What range and precision do you need? A 32-bit fixed-point number canrepresent 232 separate values between zero and 4,294,967,296 for integer-onlyarithmetic and between zero and 2.3283064365E-10 for fractional arithmetic or acombination of the two.

If you use a doubleword as your basic data type, with theupper word for integers and the lower one for fractions, you have a range of1.52587890625E-5 to 65,535 with a resolution of 4,294,967,296 numbers.Many of the routines in FXMATH.ASM were written with 64-bit fixed-pointnumbers in mind: 32 bits for integer and 32 bits for fraction.

This allows a range of2.3283064365E- 10 to 4,294,967,295 and a resolution of 1.84467440737E30 numbers, which is sufficient for most applications. If your project needs a wider range,you can write specialized routines using the same basic operations for all of them;only the placement of the radix point will differ.Significant BitsWe normally express decimal values in the language of the processor-binary.A 16-bit binary word holds 16 binary digits (one bit per digit) and can represent65,536 binary numbers, but what does this mean in terms of decimal numbers? To87NUMERICAL METHODSestimate the number of digits of one base that are representable in another, simplyfind ceil(logaBn), where a is the target base, B is the base you’re in, and n is the poweror word size.

For example, we can represent a maximum ofdecimal-digits = 5 = ceil((log10(216))in a 16-bit binary word (a word on the 8086 is 16 bits, 216 = 65536, and log10 65536= 4.8, or five decimal digits). Therefore, we can represent 50,000 as c350H, 99.222Das 63.39H, and .87654D as .e065H.Note: A reference to fixed-point or fractional arithmetic refers to binary fractions.For the purposes of these examples, decimal fractions are converted to hexadecimalby multiplying the decimal fraction by the data type. To represent .5D in a byte, or256 bits, I multiply .5 by 256.

The result is 128, or 80H. These are binary fractionsin hexadecimal format. Results will be more accurate if guard digits are used forproper rounding. Conversion to and from fixed-point fractions is covered in Chapter5.We can express five decimal numbers in 16 bits, but how accurately are we doingit? The Random House dictionary defines accuracy as the degree of correctness ofa quantity, so we could say that these five decimal digits are accurate to 16 bits. Thatis, our representation is accurate because it’s correct given the 16 bits of precisionwe’re using, though you still may not find it accurate enough for your purposes.Clearly, if the fraction cannot be expressed directly in the available storage or isirrational, the representation won’t be exact.

In this case, the error will be in the LSB;in fact, it will be equal to or less than this bit. As a result, the smallest valuerepresentable (or the percent of error) is shown as 2-m, where m is the number offraction bits. For instance, 99.123D is 63.1fH accurate to 16 bits, while 63.1f7cH isaccurate to 24 bits.

Actually, 63.lfH is 99.121D and 63.lf7cH is 99.12298, but eachis accurate within the constraints of its precision. Assuming that no extendedprecision is available for rounding, no closer approximation is possible within 16 or24 bits. The greater the precision, the better the approximation.88REAL NUMBERSThe Radix PointThe radix point can occur anywhere in a number. If our word size is 16 bits, wecan generally provide eight bits for the integer portion and eight bits for the fractionalportion though special situations might call for other forms.

Floating point involvesfixed-point numbers between 1.0 and 2.0. In a 24-bit number, this leaves 23 bits forthe mantissa. The maximum value for a sine or cosine is 1, which may not even needto be represented, leaving 16 bits of a 16-bit data type for fractions. Perhaps you onlyneed the fraction bits as guard digits to help in rounding; in such cases you mightchoose to have only two bits, leaving the rest for the integer portion.Depending on your application, you may want a complete set of fixed-pointroutines for each data type you use frequently (such as 16- and 32-bit) and use otherroutines to address specific needs. In any event, maintaining the radix point (scaling)requires more from the programmer than does floating point, but the results, in termsof both speed and code size, are worth the extra effort.The nature of the arithmetic doesn’t change because of the radix point, but theradix point does place more responsibility on the programmer.

Your software mustknow where the radix point is at all times.RoundingIf all the calculations on a computer were done with symbolic fractions, the errorinvolved in approximating fractions in any particular base would cease to exist. Thearithmetic would revolve around multiplications, divisions, additions, and subtractions of numerators and denominators and would always produce rational results.The problem with doing arithmetic this way is that it can be very awkward, timeconsuming, and difficult to interpret in symbolic form to any degree of precision.On the other hand, real numbers involve error because we can’t always expressa fraction exactly in a target base.

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

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

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

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