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

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

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

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

If the result of the subtraction, which must be in AL, is greaterthan nine, AH is decremented and six is subtracted from AL. If AH is zero, itbecomes -1 (0ffH).The purpose of these functions is to allow a small amount of decimal arithmeticin ASCII form for I/O. They may be sufficient to drive displays and do simple stringor keyboard handling, but if your application does enough number crunching-andit doesn’t take much-you’ll probably want to do it in binary; it’s much faster andeasier to work with.Radix ConversionsIn his book Seminumerical Algorithms, Donald Knuth writes about a number ofmethods for radix conversion1.

Four of these involve fundamental principles and arewell worth examining.These methods are divided into two groups: one for integers and one forfractions. Note: properly implemented, the fractional conversions will work withintegers and the integer conversions with the fractions. In the descriptions thatfollow, we’ll convert between base 10 and base 2.

Base A will be the base we’reconverting from, and base B will be the base we’re converting to. The code in thissection uses binary arithmetic, often with hexadecimal notation, because that’s thenative radix of most computers and microprocessors. In addition, all conversions arebetween ASCII BCD and binary, but you can use these algorithms with any radix.Integer Conversion by DivisionIn this case, base A (2) is converted to base B (10) by division using binaryarithmetic. We divide the number to be converted by the base we’re converting to andplace it in a variable. This is a modular operation, and the remainder of the divisionis the converted digit. The numbers are converted least significant digit first.If we were to convert 0ffH (255D) to decimal, for example, we would first divideby 0aH (10D).

This operation would produce a quotient of 19H and a remainder of5H (the 5 is our first converted digit). We would then divide 19H by 0aH, for aresulting quotient of 2H and a remainder of 5H (the next converted digit). Finally,165NUMERICAL METHODSwe would divide 2H by 0aH, with a 0H result and a 2H remainder (the final digit).Briefly, this method works as follows:1.Shift the bits of the variable decimal_accumulator right four bits to make roomfor the next digit.2. Load an accumulator with the value to be converted and divide by 0aH (10D).3.OR the least significant nibble of decimal_accumulator with the four-bitremainder just produced.4.Check the quotient to see that there is something left to divide.If so, continue with step 1 above.If not, return decimal_ accumulator as the result.The routine bn_dnt converts a 32-bit binary number to an ASCII string.

Theroutine expects no more than eight digits of decimal data (you can change this, ofcourse).This routine loads the number to be converted into AX, checks it for zero, andif possible divides it by 10. Because the remainder from the first division is alreadyin DX, we don’t have to move it to prepare for the second division (on the LSW). Theremainder generated by these divisions is ORed with zero, resulting in an ASCIIcharacter that’s placed in a string.

The conversion is unsigned (we’ll see examplesof signed conversions later in this chapter).bn_dnt: Algorithm1.Point to the binary value, binary, to be converted and to the outputstring, decptr. Load the loop counter for maximum string size.2.Get the MSW of binary and check for zero.If it's zero, continue with step 6.If not, divide by 10.Return the quotient to the MSW of binary.Check the remainder for zero.If it's zero, continue with step 6.If not, go on to step 3.3.166Get the LSW of binary and check for zero.INPUT, OUTPUT, AND CONVERSIONIf it's zero, check the remainder from the last division.

If it's alsozero, continue with step 5.Otherwise, continue with step 4.4. Divide by 10 and return the quotient to the LSW of binary.5. Make the result ASCII by ORing zero (30H). Write it to the string,increment the pointer,and decrement the loop pointer,If the loop counter isn't zero, continue with step 2.Otherwise, exit with an error.6. Test the upper word of binary for zero.If it's not zero, go to step 3.Ifit's,check the LSW of the binary variable.If it's not zero, go to step 4.If it's, we're done; go to step 7.7. Realign the string and return with the carry clear.bn-dnt: Listing; bn_dnt - a routine that converts binary data to decimal;;A doubleword is converted.

Up to eight decimal digits are;placed in the array pointed to by decptr. If more are required to;convert this number, the attempt is aborted and an error flagged.;bn_dnt proc uses bx cx dx si di, binary:dword, decptr: wordleasi,word ptr binarymovmovadddi,word ptr decptrcx, 9di,cxsubmovmovbx,bxdx,bxbyte ptr [di],bldecdibinary_conversion:submovdx, dxax,word ptr [si][2];get pointer to MSB of;decimal value;string of decimal ASCII digits;point to end of string;this is for correct ordering;see that string is zero;terminated;get upper word167NUMERICAL METHODSorjedivmovorjedivide_lower:movorjneorjenot_zero:divput_zero:movorax,axchk_emptyitenword ptr [si][2],axdx, dxchk_empty;see if it is zero;if so, check empty;divide by 10ax, word ptr [si];always checking the least;significant word;of the binary accumulator;for zeroax,axnot_zerodx, axput_zeroiten;divide lower wordword ptr [si],axdl,'O';save quotient;make the remainder an ASCII;digit;write it to a stringmovdecloopbytr, [di], dldibinary_conversionmovstcretax,-1;too many characters; just leaveoops:chk_empty:orjejmpstill_nothingmovbinaryorjejmpempty:incmov168;check for zerosdx,ax;we are done if the variable;ls emptystill_nothingshort divide_lowerax, word ptr [si];check least significant word ofax, axemptyshort not_zero;variable for zerodisi, di;realign string;trade pointersINPUT, OUTPUT, AND CONVERSIONrepmovmovmovswfinished:subclcretbn_dnt endpdi, word ptr decptrcx, 9ax,ax;success;no carry = success!Integer Conversion by MultiplicationIn this case, base A (10) is converted to base B (2) by multiplication using binaryarithmetic.

We convert the number by multiplying the result variable, calledbinary-accumulator, by base A (10), before adding each new decimal digit.To see how this is done, we can reverse the conversion we just completed. Thistime, we wish to convert 255D to binary. First we create an accumulator, binvar, tohold the result (which is initially set to 0) and a source variable, decvar, to hold thedecimal value. We then add decimal digits to binvar one at a time from decvar whichis set to 255D. The first iteration places 2D in binvar; we multiply this by 0aH (10D)to make room for the next addition.

(Recall that the arithmetic is binary.) Binvar isnow 14H. The next step is to add 5D. The result, 19H, is then multiplied by 0aH toequal 0faH. To this value we add the final digit, 5D, to arrive at the result 0ffH(255D). This is the last digit, so no further multiplications are necessary.Assume a word variable, decvar, holds four packed decimal digits. Thefollowing pseudocode illustrates how these digits are converted to binary and theresult placed in another word variable, binvar.1. Assume binvar and decvar are word variables located somewhere in RAM.2. Multiply binvar by base A (10), the routine is converting from base A to base B.3.Shift a digit (starting with the most significant) from decvar into binvar.4.Test decvar to see whether it is zero yet.If it is, we are done and write binvar to memory or return it as the result.If not, continue from step 2.169NUMERICAL METHODSIn the following code, a pointer to a string of ASCII decimal digits is passed toa subroutine that, in turn, returns a pointer to a doubleword containing the binaryconversion.

The routine checks each digit for integrity before processing it. If itencounters a nondecimal character, it assumes that it has reached the end of thestring. Multiplication by 10 is performed in-line to save time.dnt_bn: Algorithm1.Point at the base of the BCD ASCII string (the most significant decimaldigit), clear the binary accumulator, and load the loop counter with themaximum string length.2.Get the ASCII digit and test to see whether it is between 0 and 9,If not, we are done; exit through step 4.If so, call step 5 to multiply the binary accumulator by 10. Coerce theASCII digit to binary, add that digit to the binary accumulator,increment the string pointer, and decrement the loop counter.If the loop counter is zero, go to step 3.If not, continue with step 23.Exit with error.4.

Write the binary accumulator to output and leave with the carry clear.5. Execute in-line code to multiply DX:BX by 10.dnt_bn: Listing; *****; dnt_bn - decimal integer to binary conversion routine;unsigned; It is expected that decptr points at a string of ASCII decimal digits.;Each digit is taken in turn and converted until eight have been converted;or until a nondecimal number is encountered.;This might be used to pull a number from a communications buffer.;Returns with no carry if successful and carry set if not.dnt bn proc170uses bx cx dx si di, decptr:word, binary:wordmovsi,word ptr decptrsubmovax,axbx,ax;get pointer to beginning of;BCD ASCII string;clear some registersINPUT, OUTPUT, AND CONVERSIONmovmovdecimal_conversion:movcmpjbcmpjacallxoraddadcincloopdx,bxcx, 9al,byte ptr [si]al,'O'work_doneal, '9'work_donenear ptr times_tena1,'O'bx,axdx,0sidecimal_conversion;check for decimal digit;if it gets past here, it;must be OK;in-line multiply;convert to number;add next digit;propagate any carriesoops:;more than eight digitsstcretwork_done:movmovmovclcrettimes_ten:pushdi, word ptr binaryword ptr [di],bxword ptr [dil[2],dxaxpushshlcxbx,lrclmovdx,1ax,bxmovcx, dxshlrclbx,ldx,lshlrclbx,ldx,l;store result;success;save these, they contain;information;l0 = three left shifts and;an add;this is the multiply by two;keep it171NUMERICAL METHODSaddadcpoppopretndnt_bnendpdx,cxcxax;this is the multiply by eight;add the multiply by two to;get 10;get it backFraction Conversion by MultiplicationThe next algorithm converts a fraction in base A (2) to base B (10) by successivemultiplications of the number to be converted by the base to which we’re converting.First, let’s look at a simple example.

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

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

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

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