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

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

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

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

These techniques are used for other conversions as well, such asconverting between English and metric units or between system-dependent factorssuch as revolutions and frequency. Tables are also used for such things as facilitatingdecimal arithmetic, multiplication, and division; on a binary machine, these operations suffer increased code size but make up for that in speed.For all their positive attributes, table-driven conversions have a major drawback:a table is finite and therefore has a finite resolution. Your results depend upon theresolution of the table alone. For example, if you have a table-driven routine forconverting days to seconds using a table that has a resolution of one second, an inputargument such as 16.1795 days, which yields 1,397,908.8 seconds will only resultin only 1,397,908 seconds.

In this case, your result is almost a full second off theactual value.Such problems can be overcome with a knowledge of what input the routine willreceive and a suitable resolution. Another solution, discussed in the next chapter, islinear interpolation; however, even this won’t correct inexactitudes in the tablesthemselves. Just as fractions that are rational in one base can be irrational in another,any translation may involve inexact approximations that can compound the error inwhatever arithmetic the routine performs upon the table entry. The lesson is toconstruct your tables with enough resolution to supply the accuracy you need withthe precision required.The following covers conversion from hex to ASCII, decimal to binary, andbinary to decimal using tables.Hex to ASCIIThe first routine, hexasc, is a very simple example of a table-driven conversion:from hex to ASCII.The procedure is simple and straightforward. The table, hextab, contains theASCII representations of each of the hex digits from 0 through f in order.

This is an179NUMERICAL METHODSimprovement over the ASCII convention, where the numbers and alphabet are notcontiguous. In the order we’re using, the hex number itself can be used as an indexto select the appropriate ASCII representation.Because it uses XLAT, an 8086-specific instruction, this version of the routineisn’t very portable, though it could conceivably be replaced with a move involvingan index register and an offset (the index itself). Before executing XLAT, the userplaces the address of the table in BX and an index in AL.

After XLAT is executed,AL contains the item from the table pointed to by the index. This instruction is usefulbut limited. In the radix conversion examples that follow, other ways of indexingtables will be presented.Hexasc takes the following steps to convert a binary quadword to ASCII hex.hexasc: Algorithm1.SI points to the most significant byte of the binary quadword, DI pointsto the output string, BX points to the base of hextab, and CX holds thenumber of bytes to be converted.2.The byte indicated by SI is pulled into AL and copied to AH.3.Since each nibble contains a hex digit, AH is shifted right four timesto obtain the upper nibble.

Mask AL to recover the lower nibble.4.Exchange AH and AL so that the more significant digit is translated first.5.Execute XLAT. AL now contains the ASCII equivalent of whatever hex digitwas in AL.6.Write the ASCII character to the string and increment DI.7.Exchange AH and AL again and execute XLAT.8.Write the new character in AL to the string and increment DI.9.Decrement SI to point to the next lesser significant byte of the hexnumber.10.

Execute the loop. When CX is 0, it will automatically exit and return.hexascs Listing; ******;;;;hex-to-ASCII conversion using xlatsimple and common table-driven routine to convert from hexadecimalnotation to ASCIIquadword argument is passed on the stack, with the result returned180INPUT, OUTPUT, AND CONVERSION; in a string pointed to by sptr.datahextab byte'O', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ;table of ASCII;characters.codehexasc procleamovmovmovmake ascii:movmovshrshrshrshrandxchgxlatmovincxchgxlatmovincdecloopsubmovuses bx cx dx si di, hexval:qword, sptr:wordsi,di,bx,cx,byte ptr hexval[7]word ptr sptroffset byte ptr hextab8;point to MSB of hex value;point to ASCII string;offset of table;number of bytes to be;convertedal, byte ptr [si]ah, alah,1ah,1ah,1ah,1al, 0fhal,ah;get hex byte;copy to ah to unpack;shift out lower nibblebyte ptr [di],aldial, ah;write ASCII byte to stringbyte ptr [di],aldisimake ascii;write to string;increment string pointer;decrement hex byte pointeral, albyte ptr [di],al;strip higher nibble;high nibble first;now the lower nibble;NULL at the end of the;string181NUMERICAL METHODSrethexasc endpDecimal to BinaryClearly, the table is important in any table-driven routine.

The next twoconversion routines use the same resource: a table of binary equivalents to the powersof 10, from 109 to 10-10. The problem with table-driven radix conversion routines,especially when they involve fractions, is that they can be inaccurate. Many of thenegative powers of base 10 are irrational in base 2 and make any attempt atconversion merely an approximation. Nevertheless, tables are commonly used forsuch conversions because they allow a direct translation without requiring theprocessor to have a great deal of computational power.The first example, tb_dcbn, uses the tables int_tab and frac_tab to convert aninput ASCII string to a quadword fixed-point number.

It uses the string’s positionaldata-the length of the integer portion, for instance— to create a pointer to the correctpower of 10 in the table. After the integer is converted to binary, it is multiplied bythe appropriate power of 10. The product of this multiplication is added to aquadword accumulator. When the integer is processed, the product is added to themost significant doubleword; when the fraction is processed, the product is added tothe least significant doubleword (the radix point is between the doublewords).Before the actual conversion can begin, the routine must determine the power of10 occupied by the most significant decimal digit.

It does this by testing each digitin turn and counting it until it finds a decimal point or the end of the string. It usesthe number of characters it counted to point to the correct power in the table. Afterdetermining the pointer’s initial position, the routine can safely increment it in therest of the table by multiplying consecutive numbers by consecutive powers of 10.tb-dcbn: Algorithm1.Form a pointer to the fixed-point result (the ASCII string) and to thebase address of the integer portion of the table.

Clear the variable tohold the fixed-point result and the sign flag. Set the maximum numberof integers to nine.2.Examine the first character.182INPUT, OUTPUT, AND CONVERSIONIf it's a hyphen, set the sign flag, increment the string pointer pastthat point, and reset the pointer to this value. Get the next characterand continue with step 3.If it's a "+," increment the string pointer past that point and resetthe pointer to this value. Get the next character and continue with step3.3.If it's a period save the current integer count, set a new count for thefractional portion, and continue with step 2.4.If it's the end of the string, continue with step 5.If it's not a number, exit through step 10.if it's a number, increment the number counter.5.Test the counter to see how many integers have been processed.If we have exceeded the maximum, exit through step 12.If the count is equal to or less than the maximum, increment the stringpointer, get a new character and test to see whether we are countingintegers or fractions,If we are counting integers, continue with step 3.If we are counting fractional numbers, continue with step 4.6.Get the integer count, convert it to hex, and multiply it by four (eachentry is four bytes long) to index into the table.7.Get a character.If it's a period continue with step 8.If it's the end of the string, continue with step 10.If it's a number, deASCIIize it, multiply it by the four-byte table entry,and add the result to the integer portion of the fixed-point resultvariable.

Increment the string pointer and increment the table pointerby the size of the data type.Continue with step 7.8.Increment the string pointer past the period.9.Get the next character.If it's the end of the string, continue with step 10.If not, deASCIIize it and multiply it by the next table entry, addingthe result to the fixed-point variable. Increment the string pointer andincrement the table pointer by the size of the data type. Continue withstep 9.183NUMERICAL METHODS10. Check the sign flag.If it's set, two's-complement the fixed-point result and exit withsuccess.If it's clear, exit with success.11.

Not a number: set AX to -1 and continue with step 12.12. Too big. Set the carry and exit.tb-dcbn: Listing; ******; table-conversion routines.dataint tabdwordfrac_tabdwordtab_enddword3b9aca00h,000186a0h,0000000ah,1999999ah,0000a7c5h,00000004h00000000h05f5e100h,00002710h,0000000lh028f5c29h,0000l0c6h,00989680h, 000f4240h000003e8h, 00000064h00418937h, 00068db9h00000ladh, 0000002ah;.code; converts ASCII decimal to fixed-point binary;uses bx cx dx si di.tb_dcbnprocsptr:word, fxptr:wordlocalsign:byterep184movmovleadi, word ptr sptrsi, word ptr fxptrbx, word ptr frac_tab;point to result;point to ascii string;point into tablemovsubsubstoswcx,4ax,axdx,dx;clear the target variablemovdi, word ptr sptr;point to resultINPUT, OUTPUT, AND CONVERSIONmovmovmovcl,alch,9hbyte ptr sign, al;to count integers;max int digits;assume positivemovcmpjecmpjeal, byte ptr [si]al '-'negativeal,'+'positive;get character;check for sign;count:;count the number of;characters in the stringcmpjechk_frac:cmpjecmpjbcmpjacntnu:inccmpjaincmovoral,'.'fnd_dotjnejmpfnd_dot:movincmovxchgjmpnegative:notpositive:incmovmovchk_fracshort countal,0gotnumbera1,'0'not_a_numbera1,'9'not_a_number;end of string?clcl,chtoo_bigsial, byte ptr [si]dh,dh;count;check size;is it a number then?;next character;get character;are we counting int;or frac?;count characters in intdh,cldhd1,13hch,dlshort cntnu;switch to counting fractions;can't be zero;includes decimal pointsign;make it negativesiword ptr fxptr,sial, byte ptr [si];get a character185NUMERICAL METHODSjmpgotnumber:subxchgdecshlshlsubsubshort countch,chcl,dhclword ptr cx,lword ptr cx,lbx,cxcx, cx;get int count;multiply by four;index into table;don't need integer count;anymore;point at string againmovcnvrt_int:movcmpjecmpjesubmovmulcl,byte ptr [si]cl,'.'handle_fractioncl,0do_signcl, '0'ax,word ptr [bx][2]cxaddadcmovmulword ptr [di][4],axwordax,word ptr [bx]cxaddadcaddincjmpword ptr [dil[4],axword ptr [di][6],dxbx,4sishort cnvrt_int;drop table pointersi;skip decimal pointcl,byte ptr [si]cl,0do_signcl,'O'ax,word ptr [bx][2];get first characterhandle_fraction:inccnvrt_frac:movcmpjesubmovmul186si,word ptr fxptrcx;get first character;go do fraction, if any;end of string;multiply by deASCIIized-input;multiply by deASCIIizedinput;end of string;this can never result;in a carry;multiply by deASCIIized;inputINPUT, OUTPUT, AND CONVERSIONaddmovmulword ptr [di][2],axax,word ptr [bx]cxaddadcaddincjmpword ptr [di][0],axword ptr [di][2],dxbx,4sishort cnvrt_fracdo_sign:movorjenotnotnotnegjcaddadcadcexit:ret;not_a_numbersubnottoo_big:stcjmptb_dcbnal,byte ptr signal,alexitword ptr [di][6]word ptr [di][4]word ptr [di][2]word ptr [di]exitword ptr [di] [2],1word ptr [di] [4],0word ptr [di] [61,0ax,axax;multiply by deASCIIized;input;drop table pointer;check sign;it is positive;-1;failureshort exitendpBinary to DecimalThe binary-to-decimal conversion, tb_bndc, could have been written in the samemanner as tb_dcbn—using a separate table with decimal equivalents to hex positional data.

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

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

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

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