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

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

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

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

Loadcontinue with step 9.140first operand to exponent, moveholding the sign of the largestoperand to the variable holdingthis fixed-point operand intothe signoperand,the signopa andFLOATING-POINT ARITHMETICThe FLADD Routine: Which Operand is Largest?find_largest:cmpjetestjejmpbyte ptr diff,0cmp_restbyte ptr diff,80hnuma_biggershort numb_biggercmp_rest:cmpjajbcmpjajbcmpjbdx, word ptr fp0[4]numb_biggernuma_biggerbx, word ptr fp0[2]numb_biggernuma_biggerax, word ptr fp0[0]numa_bigger;test for negative;if above;if below;defaults to numbnumb_bigger:submovnegmovcmpjnaax, axal,byte ptr diffalbyte ptr diff,alal,60in range; *****leasi,word ptr fp1[6]leave_with_largest:movaddmovmovswrepjwrange_errora:leajmpdi,word ptr rptrdi,6cx,4;save difference;do range test;this is an exit!!!!!;this is a range error;operands will not;line up;for a valid addition;leave with largest;operand;that is where the;significance is anywayfp_addexsi,word ptr fp0[6]short leave_with_largest; *****141NUMERICAL METHODSin range:movmovrepmovmovmovmovlealeamovmovswal,byte ptr explbyte ptr exponent,alal, byte ptr sign1signa, alal, byte ptr sign0byte ptr signb, alsi, word ptr fp1[6]di,word ptr opa[6]cx,4signb_positive:leajmpsi, word ptr fp0[4]shift_into_positionnuma_bigger:submovcmpjaemovmovmovmovmovmovleaax, axal,byte ptr diffal,60range erroraal,byte ptr exp0byte ptr exponent,alal, byte ptr sign1byte ptr signb, alal, byte ptr sign0byte ptr signa, alsi, word ptr fp0[6]repleamovmovswlea;save exponent of largest;value;load opa with largest operand;set to load opb;do range test;save exponent of largest value;load opa with largest;operanddi,word ptr opa[6]cx,4si, word ptr fp1[4];set to load opbThe FLADD Routine: Aligning the Radix Points.9.Divide diff by eight to determine how many bytes to shift the smalleroperand so it aligns with the larger operand.Adjust the remainder to reflect the number of bits yet to be shifted,and store it in AL.Subtract the number of bytes to be shifted from a maximum of four and142FLOATING-POINT ARITHMETICadd this to a pointer to opb.

That gives us a starting place to writethe most significant word of the smaller operand (we're writingdownward).10. Write as many bytes as will fit in the remaining bytes of opb. Move theadjusted remainder from step 9 to CL and test for zero.If the remainder is zero, no more shifting is required; continue withstep 12.Otherwise,continue at step 11.11.

Shift the smaller operand bit by bit until it's in position.12. Compare the signs of the larger and smaller operands.If they're the same, continue with step 14.If the larger operand is negative, continue with step 13.Otherwise, subtract the smaller operand from the larger and continue withstep 15.13. Two's-complement the larger operand.14. Add the smaller operand to the larger and return a pointer to the result.The FLADD Routine: Aligning the Radix Pointshift_into_position:;align operandsxormovmovmovshrax,axbx,4cl,3ah,byte ptr diffax,clmovshrsubcx,5hal,clbl,ahleaaddmovincload_operand:movsbloopmovxoror;ah contains # of bytes,;a1 # of bits;reset pointer below initial;zerosdi,byte ptr opbdi,bxcx,bxcxload_operandcl,alch,chcx, cx143NUMERICAL METHODSjeshift_operand:shrrcrrcrrcrloopend_shift:movcmpjeopb_negative:notnotnotnegjcadcadcadcjust_add:invokeend shiftword ptr opb[6],1word ptr opb[4],1word ptr opb[2],1word ptr opb[0],lshift_operandal, byte ptr signaal, byte ptr signbjust_addword ptrword ptrword ptrword ptrjust_addword ptrword ptrword ptropb[6]opb[4]opb[2]opb[0];signs alike, just add;do two's complementopb[2],0opb[41,0opb[6],0add64, opa, opb, rptrFLADD: The Epilogue.15.

Test the result of the fixed-point addition for zero. If it's zero, leavethe routine and write a floating-point zero to output.16. Determine whether normalization is necessary and, if so, whichdirectionto shift.If the most significant word of the result is zero, continue with step18.If the MSB of the most significant word is zero, continue with step 17.If the MSB of the second most significant byte of the result (the hiddenbit) isn't set, continue with step 18.Otherwise, no shifting is necessary; continue with step 19.17.

Shift the result right, incrementing the exponent as you go, until thesecond most significant byte of the most significant word is set. Thiswill be the hidden bit. Continue with step 19.18. Shift the result left, decrementing the exponent as you go, until thesecond most significant byte of the most significant word is set. This144FLOATING-POINT ARITHMETICwill be the hidden bit. Continue with step 19.19. Shift the most significant word left once to insert the exponent. Shiftit back when you're done, then or in the sign.20.

Write the result to the output and return.FLADD: The Epiloguehandle_sign:movmovmovmovsi,dx,bx,ax,wordwordwordwordptrptrptrptrrptr[si][4][si][2][si][0]norm:subcx,cxax, cxcmpjnenot_zerobx,cxcmpjnenot_zerodx,cxcmpjnenot_zerowrite_resultjmpnot_zero:movcx,64dx,0hcmprotate_result_leftjedh,00hcmpjnerotate_result_righttestd1,80hrotate_result_leftjeshort_done_rotatejmprotate_result_right:shrdx,1rcrbx,lrcrax,1incbyte ptr exponenttestjelooprotate_result_left:shlrcl;exit with a zero;decrement exponent with;each shiftdx,0ff00hdone rotaterotate result rightax,1bx,l145NUMERICAL METHODSrcldecdx,1byte ptr exponenttestjneloopdone rotate:andshlorshrmovdx,80hdone rotaterotate result leftorjeorfix-sign:movorjeorwrite result:movmovmovmovsubmovfp_addex:popfretfladd endpcl, clfix signdx,8000hdx,7fhdx 1dh, byte ptr exponentdx, 1cl, byte ptr signcl, byte ptr signacl, clwrite resultdx,80;0h;decrement exponent with;each shift;insert exponent;sign of result of;computation;sign of larger operanddi,word ptr rptrword ptr [di],axword ptr [di][2],bxword ptr [di][4],dxax,axword ptr [di][6],axAt the core of this routine is a fixed-point subroutine that actually does thearithmetic.

Everything else involves extracting the fixed-point numbers from thefloating-point format and aligning. Fladd calls add64 to perform the actual addition.(This is the same routine described in Chapter 2 and contained in the FXMATH.ASMlisting in Appendix C and included on the accompanying disk). It adds two quadwordvariables passed on the stack with multiprecision arithmetic and writes the output toa static variable, result.146FLOATING-POINT ARITHMETICMultiplication and DivisionOne minor difference between the multiplication and division algorithms is theerror checking at the entry point.

Not only are zero and infinity tested in the prologueto division as they are in the prologue to multiplication, we also check to determinewhether the operands are the same. If they are identical, a one is automaticallyreturned, thereby avoiding an unnecessary operation.Floating point treats multiplication and division in a manner similar to logarithmic operations. These are essentially the same algorithms taught in school for doingmultiplication and division with logarithms except that instead of log,,, theseroutines use log2. (The exponent in these routines is the log, of the value beingrepresented.) To multiply, the exponents of the two operands are added, and to dividethe difference between the exponents is taken. Fixed point arithmetic performs themultiplication or division, any overflow or underflow is handled by adjusting theexponents, and the results are renormalized with the new exponents.

Note that thevalues added and subtracted as the biases aren’t exactly 127D. This is because of themanner in which normalization is accomplished in these routines. Instead oforienting the hidden bit at the MSB of the most significant word, it is at the MSB ofthe penultimate byte (in this case DL). This shifts the number by 8 bits, so the biasthat is added or subtracted is 119D.FLMULThe pseudocode for floating point multiplication is as follows:flmul: Algorithm1. Check each operand for zero and infinity.If one is found to be infinite, exit through step 9.If one is found to be zero, exit through step 10.2.Extract the exponent of each operand, subtract 77H (119D) from one ofthem, and add to form the approximate exponent of the result.3.Test each operand for sign and set the sign variable accordingly.4.Restore the hiddenbit in eachoperand.

Now each operand is a fixed-pointnumber in the form 1.XXXX...147NUMERICAL METHODS5.Multiply the two numbers with the fixed-point routine mu164a.6. Check the result for zero. If it is zero, exit through step 10.7.Renormalize the result, incrementing or decrementing the exponent at thesame time.

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

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

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

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