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

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

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

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

This routine was specifically written toperform the fixed-point divide.RoundingRounding is included in this discussion on floating point because it’s used in theexternal routines.IEEE 754 says that the default rounding shall “round to nearest,” with the optionto choose one of three other forms: round toward positive infinity, round to zero, andround toward negative infinity.

Several methods are available in the roundingroutine, as you’ll see in the comments of this routine.The default method in round is “round to nearest.” This involves checking theextended bits of the floating-point number. If they’re less than half the LSB of theactual float, clear them and exit. If the extended bits are greater than half the LSB,add a one to the least significant word and propagate the carries through to the mostsignificant word. If the extended bits are equal to exactly one-half the LSB, thenround toward the nearest zero. If either of the last two cases results in an overflow,increment the exponent. Clear AX (the extended bits) and exit round.

If a faultoccurs, AX contains -1 on exit.round: Algorithm1. Load the complete float, including extended bits, into the microprocessor's159NUMERICAL METHODSregisters.2.Compare the least significant word with one-half (8000H).If the extended bits are less than one-half, exit through step 5.If the extended bits aren't equal to one-half, continue with step 3.If the extended bits are equal to one-half, test the LSB of therepresentable portion of the float.If it's zero, exit through step 5.If it's one, continue with step 3.3.Strip the sign and exponent from the most significant word of the floatand add one to the least significant word.

Propagate the carry by addingzero to the upper word and test what might have been the hidden bit fora one.A zero indicates that no overflow occurred; continue with step 4.A one indicates overflow from the addition. Get the most significant wordof the float, extract the sign and exponent, and add one to the exponent.If this addition resulted in an overflow, exit through step 5.Insert the new exponent into the float and exit through step 5.4.Load the MSW of the float. Get the exponent and sign and insertthem into the rounded fixed-point number; exit through step 5.5.Clear AX to indicate success and write the rounded float to the output.6.

Return a -1 in AX to indicate failure. Make the float a Quiet NAN (positiveoverflow) and exit through step 5.Round: Listing; *****round proto flp0:qword, rptr:wordround procmovmovmovcmpjbjnetestje160uses bx dx di, fp:qword, rptr:wordax,word ptr fp[0]bx,word ptr fp[2]dx,word ptr fp[4]ax,8000hround exneeds_roundingbx,lround_ex;less than half;put your rounding scheme;here, as in the;commented-out code belowFLOATING-POINT ARITHMETIC;jmpxorshort needs roundingx, 1;orbx,1jmpneeds rounding:andaddadctestjemovandandaddjoorjmprenorm:movandorround_ex:subround_exl:movmovmovmovsubmovretover_flow:xormovnotmovxorjmpround endp;round to even if odd;and odd if even;round down if odd and up if;even (jam)round_exdx,7fhbx,1hdx,Odx,80hrenormax,word ptr fp[4]dx, 7fhax,0ff80hax,80hover flowdx,axshort round_exax,word ptr fp[4]ax,0ff80hdx,ax;if this is a one, there will;be an overflow;get exponent and sign;kick it up one;get exponent and signax,axdi,word ptr rptrword ptr [di][0],axword ptr [di][Z],bxword ptr [di][4],dxax,axword ptr [di][6],axax,axbx,axaxdx,axdx,7fH;indicate overflow with an;infinityshort round ex1161NUMERICAL METHODS1Ochs, Tom.

“A Rotten Foundation,” Computer Language 8/2: Page 107.Feb. 1991.2Knuth, D. E. Seminumerical Algorithms. Reading, MA: Addison-Wesley Publishing Co., 1981, Pages 213-223.3IEEE Standard for Binary Floating-Point Arithmetic (ANSI/IEEEStd 754, 1985).4Plauger, P.J. “Floating-Point Arithmetic,” Embedded Systems Programming 4/8: Pages 95-100. Aug. 1991.162Previous HomeCHAPTER 5Input, Output,and ConversionTo be useful, an embedded system must communicate with the outside world.How that communication proceeds can strongly influence the system’s speed andefficiency.Often, the nature of the system and the applications program that drives it definesthe form of the commands that flow between an embedded system and the host.

Ifit’s a graphics card or servo controller embedded in a PC, the fastest way tocommunicate is pure binary for both commands and data. Depending on theavailability of a math chip, the numerics are in either fixed or floating-point notation.Even so, it’s quite common to find such systems using ASCII strings and decimalarithmetic to interface with the user. That’s because binary communication can befast, even though it has its problems. The General Purpose Interface Bus (GPIB) hassome of the advantages and speed of the hardware interface, but the binary commandand data set can sometimes imitate its own bus-control commands and cause trouble.Binary information on RS232, perhaps the most commonly used interface, hassimilar problems with binary data aliasing commands and delimiters.

Packet-basedcommunications schemes are available, however, they can be slow and clumsy. Anyproblem can be solved on closed systems under controlled circumstances, butrigorous, simple communication schemes often default to ASCII or EBCDIC forease of debugging and user familiarity.Whatever choices you make for your system, it will almost always have tocommunicate with the outside world. This often means accepting and working withformats that are quite foreign to the binary on the microprocessor bus. What’s more,the numerics will most likely be decimal and not binary or hex, since that’s how mostof us view the world.163NextNUMERICAL METHODSDecimal ArithmeticIf your system does very little calculation or just drives a display, it may not beworth converting the incoming decimal data to another format.

The Z80, 8085, and8051 allow limited addition and subtraction in the form of the DAA or DA instruction.On the Intel parts, this instruction really only helps during addition; the Z80 canhandle decimal correction in both addition and subtraction. The 80x86 family offersinstructions aimed at packing and unpacking decimal data, along with adjustmentsfor a limited set of basic arithmetic operations. The data type is no greater than a byte,however, making the operation long and cumbersome to implement. The 8096family lacks any form of decimal instructions such as the DAA or auxiliary carry flag.Binary-based microprocessors do not work easily with decimal numbers because base 2, which is one bit per digit, and even base 16, which is four bits per digit,are incompatible with base 10; they have a different modulus.

The DAA instructioncorrects for this by adding six to any result greater than nine (or on an auxiliary carry),thereby producing a proper carry out to the next digit.A few other instructions are available on the 80x86 for performing decimalarithmetic and converting to and from ASCII:AAA stands for ASCII Adjust After Addition. Add two unpacked (one decimaldigit per byte) 8-bit decimal values and put the sum in AL.

If the sum is greaterthan nine, this instruction will add six but propagate the carry into AH. Thatleaves you with an unpacked decimal value perfectly suited for conversion toASCII.AAD stands for ASCII Adjust before Division, takes an unpacked value in AXand performs an automatic conversion to binary, placing the resulting value inAL. This instruction can help convert ASCII BCD to binary by handling part ofthe process for you.The AAM instruction, which stands for ASCII Adjust After Multiply, unpacksan 8-bit binary number less than 100 into AL, placing the most significant digitin AH and the least significant in AL. This instruction allows for a fast, easyconversion back to ASCII after a multiplication or division operation.AAS stands for ASCII Adjust After Subtraction, corrects radix misalignment164INPUT, OUTPUT, AND CONVERSIONafter a subtraction.

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

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

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

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