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

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

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

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

module included on the disk.Signed Addition and SubtractionWe perform signed addition and subtraction on a microcomputer much as weperform their unsigned equivalents. The primary difference (and complication)arises from the MSB, which is the sign bit (zero for positive and one for negative).Most processors perform signed arithmetic in two’s complement, the method we’lluse in this discussion.

The two operations of addition and subtraction are closelyrelated; each can be performed using the logic of the other. For example, subtractioncan be performed identically to addition if the subtrahend is two’s-complementedbefore the operation. On the 8048, in fact, it must be done that way due to the absenceof a subtraction instruction.15 - 7 = 15 + (-7) = 80fH - 7H = 0fh + 0f9H = 8HThese operations are accomplished on a microprocessor much as we performedthem in school using a pencil and paper.38INTEGERSOne aspect of using signed arithmetic is that the range of values that can beexpressed in each data type is limited.

In two’s-complement representation, therange is -2n-1 to 2n-1-1. Use signed arithmetic carefully; ordinary arithmetic processescan result in a sign reversal that invalidates the operation.Overflow occurs in signed arithmetic when the destination data type is too smallto hold the result of a signed operation-that is, a bit is carried into the MSB (the signbit) during addition and is not propagated through to the carry, or a borrow was madefrom the MSB during subtraction and is not propagated through to the carry. If eitherevent occurs, the carry flag may not be set correctly because the carry that did occurmay not propagate through the sign bit into the carry flag.Adding 60H and 50H in an eight-bit accumulator results in b0H, a negativenumber in signed notation even though the original operands were positive.

Guardagainst such overflows when using signed arithmetic.This is where the overflow flag comes in. Simply put, the overflow flag is usedto indicate that the result of a signed arithmetic operation is too large or too small forthe destination operand. It is set after two numbers of like sign are added or subtractedif the sign of the result changes or if the carry into the MSB of an operand and thecarry out don’t match.When we added 96D (60H) and 80D (50H), we got an overflow into the sign bitbut left the carry flag clear:0l0l0000B (+50H)+01100000B (+60H)l0ll0000B (b0H, or -80D)The result was a specious negative number.

In this case, the overflow flag is setfor two reasons: because we’re adding two numbers of like sign with a subsequentchange in the sign of the result and because the carry into the sign bit and the carryout don’t match.To guard against accidental overflows in addition and subtraction, test theoverflow flag at the end of each operation.Assume a 32-bit signed addition in 8086 assembler. The code might look likethis:39NUMERICAL METHODSsigned -add:movmovaddaddjoax, word ptr summendldx, word ptr summendl[2]ax, word ptr summenddx, word ptr summend2[2]bogus_result;first load one summend;into dx:ax;add the two, using the carry flag;to propagate any carry;out of the lower word;;check for a valid resultgood-result:When writing math routines, be sure to allocate enough storage for the largestpossible result; otherwise, overflows during signed operations are inevitable.Decimal Addition and SubtractionFour bits are needed to represent the decimal numbers zero through nine.

If themicrocomputer we’re using has a base 10 architecture rather than one based onbinary, we could increment the value 1001 (9D) and get 0 (0D) or decrement 0 andget 1001. We could then add and subtract decimal numbers on our machine and getvalid results. Unfortunately, most of the processors in use are base 2, so when weincrement 100l (9D) we get 1010 (0AH).

This makes performing decimal arithmeticdirectly on a microcomputer difficult and awkward.In packed binary coded decimal, a digit is stored in each nibble of a byte (asopposed to unpacked, in which a byte holds only one digit). Whenever addition orsubtraction on packed BCD results in a digit outside the range of normal decimalarithmetic (that is, greater than nine or less than zero), a special flag known as theauxiliary carry is set.

This indicates that an overflow or underflow has resultedduring a particular operation that needs correction. This is analogous to the carry bitbeing set whenever an overflow occurs. On the 80x86, this flag, in association withthe appropriate instruction—DAA for addition and DAS for subtraction-willproduce a decimally correct result on the lower byte of the AX register. Unfortunately, these instructions only work eight bits at a time and even then in only oneregister, with the operands moved into and out of AL to perform a calculation of anylength.

As limited as this is, the instructions do allow you to perform a certain amountof decimal arithmetic on a binary machine without converting to binary.40INTEGERSWhen decimal addition is performed, each addition should be followed by a DAAor its equivalent. This instruction forces the CPU to add six to a BCD digit if it isoutside the range, zero through nine, or if there has been a carry from the digit. It thenpasses the resulting carry into the next higher position. This adjusts for decimaloverflows and allows normal decimal addition to be performed correctly in a packedformat.As an example, if we add 57D and 25D on a binary machine without convertingto binary, we might first store the two values in registers in the following packedformat:A = 01010111B(57H)B = 00100101B(25H)We follow this with an ADD instruction (note that the carry is ignored here):adda,bwith the result placed in A:A = 1111100B (7cH)Because a decimal overflow occurred in the first nibble (1100B = 12D), theauxiliary carry flag is set.

Now when the DAA instruction is executed, a six is addedto this nibble and the carry propagated into the next higher nibble:1100B0ll0Bl00l0BThis leaves a two as the least significant digit with a carry into the next higherposition, which is the same as adding a one to that digit:0111 (7H)0001 (1H)1000 (8H)41NUMERICAL METHODSThe final result is 10000010B (82H).This mechanism is widely implemented on both microprocessors andmicrocontrollers, such as the 8048, 8051, Z80, 80x86, and 80376. Unfortunately,neither the decimal adjust nor the auxiliary carry flag exists on the 80C196 or theTMS34010.The DAA will work with decimal additions but not with decimal subtractions.Machines such as the Z80 and 80x86 make up for this with additional hardware tosupport subtraction.

The Z80 uses the N and H flags along with DAA, while the 80x86provides the DAS instruction.The 8086 series and the 68000 series of microprocessors provide additionalsupport for ASCII strings. On the 8086, these instructions are AAM, AAS, AAA, andAAD (see Chapter 5 for examples and greater detail). Since they do offer somearithmetic help, let’s take a brief look at them now.1AAA adjusts the result of an addition to a simple decimal digit (a value from zerothrough nine). The sum must be in AL; if the result is greater than nine, AH isincremented.

This instruction is used primarily for creating ASCII strings.AAD converts unpacked BCD digits in AH and AL to a binary number in AX.This instruction is also used to convert ASCII strings.AAM converts a number less than 100 in AL to an unpacked BCD number in AX,the high byte in AH, and the low byte in AL.AAS, similar to AAA, adjusts the result of a subtraction to a single decimal digit(a value from zero through nine).Multiplication and DivisionThis group comprises what are known as “arithmetic operations of the secondkind,” multiplication being iterative addition and division being iterative subtraction. In the sections that follow, you’ll see several algorithms for each operation,starting with the classic methods for each.The classic algorithms, which are based on iterative addition or subtraction, mayor may not be the fastest way to execute a particular operation on your target machine.42INTEGERSThough error checking must always be done for correct results, the errors that occurwith these routines don’t have the same impact on the processor state as thoseinvolving hardware instructions.

What’s more, these algorithms work in any binaryenvironment because they deal with the most fundamental elements of the machine.They often provide fast, economical solutions to specialized situations that mightprove awkward or slow with hardware instructions (see the multen routine inFXMATH.ASM). Along with the classic algorithms, there will be examples ofenhancements to these routines and some algorithms that work best in silicon;nonetheless, they’re based on arithmetic viewpoints that you may find interesting.Signed vs. UnsignedWithout special handling, multiplication or division of signed numbers won’talways result in correct answers, even if the operands themselves are sign-extended.In multiplication, a problem arises in that the number of bits in the result of themultiplication is equal to, at a minimum, the number of bits in the largest operand (ifneither operand is zero) and, at a maximum, the sum of bits in both operands (if eachoperand is equal to or greater than 2n-1, where n is the size of the data type).

It is usuallywise to provide a result data type equal in size to the number of bits in the multiplicandplus the number of bits in the multiplier, or twice the number of bits in the largestoperand. For a signed operation, this can mean the result may not have the signrequired by the operands. For example, multiplying the two unsigned integers,ffH(255D) and ffH(255D), produces fe0lH(65025D), which is correct. If, however,two numbers are signed, ffH(-1D) and ffH(-1D), the correct result is 1H(1D), notfe01H(-511D).

Further, an ordinary integer multiply knows nothing about signextension, multiplying ffH(-1D) by 1H(1D) produces ffH(255D) in a 16-bit datatype.Similar problems occur in division. Unlike multiplication, the results of a dividerequire the difference in the number of bits in the operands. That means two 8-bitoperands could require as little as one bit to represent the result of the division, or asmany as eight.

With division, it is wise to allot storage equal to the size of the dividendto account for any solution. With this in mind, dividing the two signed 8-bit operands,ffH(-1D) by 1H(1D), is no problem-in this case the result is ffH(-1D). But if the43NUMERICAL METHODSdivisor is any larger, the result is incorrect—FFH/5H = 33H, when the correctanswer is OH.Many processors offer a signed version of their multiply and divide instructions.On the 8086, those instructions are IMUL and IDIV. To use them on single-precisionoperands, be sure both operands are signed and the (byte) word sizes are compatibleso the result won’t overflow. If you attempt to multiply a signed word operand by anunsigned word operand greater than 7fffH, your result will be in error.

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

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

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

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