{"id":59,"date":"2023-07-21T23:58:49","date_gmt":"2023-07-22T03:58:49","guid":{"rendered":"https:\/\/www.vociferousvoid.org\/?p=59"},"modified":"2023-07-22T10:58:32","modified_gmt":"2023-07-22T14:58:32","slug":"the-rationality-of-irrationality","status":"publish","type":"post","link":"https:\/\/www.vociferousvoid.org\/index.php\/2023\/07\/21\/the-rationality-of-irrationality\/","title":{"rendered":"The Rationality of Irrationality"},"content":{"rendered":"\n<p>\nRationalism is a sociological philosophy which, in a general sense,\neschews the understanding of reality through mystery and magic. This\nhas parallels with computing where results can often seem\nmagical. This is doubly true when dealing with real-world numbers:\nalthough the hardware seems ill equipped to express real numerical\nvalues complex calculations are nonetheless possible.\n<\/p>\n\n\n\n<p>\nA computer represents a number as a finite string of 1s and 0s. On\nmodern computers, this string is typically 64 bits long. This means\nthat the domain of natural numbers that can be expressed in this\nsystem is countable and finite with an upper value of \\(2^{63}-1\\).\n<\/p>\n\n\n\n<p>\nUnlike natural numbers, Reals are not countable which limits their\ndomain; the subset of which can be represented by finit bit\nstrings. One approach is to use quantization. For example, each\nincrement of a binary value could correspond to a Real value of\n0.25. Therefore the bit sequence \\(b101\\) would represent the Real value\n1.25.\n<\/p>\n\n\n\n<p>\nAnother approach is to use Rational numbers, which the a subset of the\nReal numbers that can be expressed as the quotient of two natural\nnumbers: the dividend and the divisor. Therefore the rational numbers,\nwithin a given range, are also finite and countable.\n<\/p>\n\n\n\n<p>\nRational numbers cover a good portion of the range of Real values,\nhowever, Irrational numbers are also Reals and are a little bit\ntricker to express since their representation requires an infinite\nnumber of digits. Therefore the best that can be achieved is an\napproximation of irrational numbers. This means that their use in\ncalculations will introduce errors due to lack of precision. To\novercome this limitation, the values can be approximated on demand,\nand iteratively refined to obtain the desired precision. However, this\nwill add steps to the calculation which slows down the entire process.\n<\/p>\n\n\n\n<p>\nEvidently, there are many pitfalls in using integer values to express\nReal data. Real values are not countable and can therefore not be\nexpressed using countable quantities such as integers. &#8220;Squeezing\ninfinitely many real numbers into a finite number of bits requires an\napproximate representation.&#8221;<sup><a id=\"fnr.1\" class=\"footref\" href=\"#fn.1\">1<\/a><\/sup> The floating-point standard (IEEE\n754-2008<sup><a id=\"fnr.2\" class=\"footref\" href=\"#fn.2\">2<\/a><\/sup>) offers a good middle ground for dealing with Real data\nall while respecting the storage constraints of the computer&#8217;s\nregisters. However, the floating-point numbers can still only express\na subset of the Real values; the Rational numbers that can be\nrepresented as a pair of integers. This leaves out irrational numbers,\nsuch as \\(\\pi\\) and \\(e\\), which are important for calculating physical\nquantities which must be approximated; preferably in the most\nefficient way possible. An efficient procedure for approximating Real\nvalues with a very high precision is of primal importance. Especially\nif these values are used frequently.\n<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Approximately Polynomial<\/h2>\n\n\n\n<p>\nOne way to approximate Real numbers to a given precision is by\nrepresenting it as a polynomial; a series of terms that involve only\nterms that can easily be expressed by a computer. For example, the\ntrigonometric functions, \\(\\sin\\) and \\(\\cos\\), can be approximated using\nthe Taylor polynomial<sup><a id=\"fnr.3\" class=\"footref\" href=\"#fn.3\">3<\/a><\/sup> evaluated around zero. The value of \\(\\cos\nx\\) is evaluated to a precision of \\(\\cos{\\tilde{\\mathcal{E}}(x)}\\) using\nthe following series of terms:\n<\/p>\n\n\n\n<p>\n\\[\n\\cos x = 1 &#8211; \\frac{1}{2}x^2 + \\frac{1}{24}x^4\\cos{\\tilde{\\mathcal{E}}(x)}\n\\]\n<\/p>\n\n\n\n<p>\nThis is the expansion of the first three terms of the Taylor\nseries.\n<\/p>\n\n\n\n<p>\nDeriving the Taylor polynomial requires knowledge about the n-th\nderivative of the function being approximated. Fortunately, the\nderivatives of trigonometric functions have natural results for given\nvalues of \\(x\\). Moreover these values are periodic with a period of 4;\nmeaning that the 4-th derivative has the same value as the original\nfunction. Therefore the derivatives of \\(\\sin\\) and \\(\\cos\\) can be\nimplemented using a lookup table:\n<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>Derivative<\/td><td>SIN<\/td><td>COS<\/td><\/tr><tr><td>0<\/td><td>0<\/td><td>1<\/td><\/tr><tr><td>1<\/td><td>1<\/td><td>0<\/td><\/tr><tr><td>2<\/td><td>0<\/td><td>-1<\/td><\/tr><tr><td>3<\/td><td>-1<\/td><td>0<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Lookup Table for Derivatives of Sine and Cosine of zero<\/figcaption><\/figure>\n\n\n\n<p>\nGiven that the relevant values of the various derivatives of the\ntrigonometric functions are known, the result of applying one of these\nfunctions to an arbitrary number can be approximated using the Taylor\nseries.\n<\/p>\n\n\n\n<p> The following assembly code defines the <code>__taylor<\/code> function that evaluates the n-th Taylor polynomial to approximate a periodic function for a given value \\(x\\). <\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>NOTE<\/strong>: The <code>__taylor<\/code> function defines aliases for certain register names to make their usage clear.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>        #define n t0\n        #define i t3\n        #define nfact t2\n        #define x ft0\n        #define xn ft1\n__taylor:\n\tfunction_prologue 0\n        fmv.d           x, fa0\n        fmv.d           xn, x\n        mv              n, zero         \/\/ n &lt;- 0\n        mv              i, zero         \/\/ i &lt;- 0\n        lb              t1, 0(a0)\n        fcvt.d.l        fa0, t1         \/\/ fa0 &lt;- f(0)\n        addi            nfact, n, 1     \/\/ (n+1)! &lt;- 1\n1:\n        addi            n, n, 1         \/\/ n &lt;- n+1\n        addi            i, i, 1         \/\/ i &lt;- i+1\n        mul             nfact, n, nfact \/\/ n! &lt;- n*(n-1)!\n        fcvt.d.l        ft2, nfact      \/\/ ft2 &lt;- n!\n        li              t1, 4\n        blt             i, t1, 2f\n        remu            i, i, t1\n2:      \/\/ f^(n)(0): n-th derivative of f(0)\n        add             t1, a0, i\n        lb              t1, 0(t1)       \/\/ t1 &lt;- f^(n)(0)\n        beqz            t1, 3f          \/\/ Short-circuit if f^(n)(0) = 0\n        fcvt.d.l        ft3, t1\n        fdiv.d          ft3, ft3, ft2   \/\/ ft3 &lt;- f^(n)(0)\/n!\n        \/\/ fa0 &lt;= f + (x^n)*f^(n)(0)\/n!\n        fmadd.d         fa0, xn, ft3, fa0\n3:\n        fmul.d          xn, xn, x       \/\/ xn &lt;- x*x^(n)\n        blt             n, a1, 1b       \/\/ while n &lt; a1\n        mul             nfact, nfact, n\n        fcvt.d.l        ft2, nfact\n        fdiv.d          fa1, xn, ft2    \/\/ fa1 &lt;- residual\n\tfunction_epilogue 0\n        ret<\/code><\/pre>\n\n\n\n<p> Several conversion instructions are used to setup the floating-point factors used to calculate the Taylor polynomial. For example, the running value for \\(n!\\) is calculated using integer instructions since its value will always be a whole number. However, it is converted to a double-precision floating-point value on <a href=\"https:\/\/bitbucket.org\/marc_perron\/risc-v\/src\/d348e5ed651e9e02ea85547dccc5459d256a001b\/trig\/trig.S#lines-112\">line 19<\/a> (the <code>fcvt.d.l<\/code> instruction) in order to be used as an operand for floating-point arithmetic. <\/p>\n\n\n\n<p> The <code>__taylor<\/code> function will use the lookup table to fetch the n-th derivative of the function on line 31. If the value of the derivative is zero, it will skip the current term. Otherwise the value is converted to a floating-point number (on line 33), divided by \\(n!\\), and scaled by the n-th power of \\(x\\) and added to the running sum. The <code>fmadd.d<\/code> instruction on line 35 is a pseudo instruction that will multiply two numbers, then add the product to a third. <\/p>\n\n\n\n<p>\nThe \\(\\cos{\\tilde{\\mathcal{E}}(x)}\\) term in the expansion of the Taylor\nseries for \\(cos x\\) represents the remainder error. As the polynomial\nis expanded to include more terms, this error value will become\nsmaller (meaning the apprximation will be closer to the actual\nvalue). Since \\(\\left|\\cos{\\tilde{\\mathcal{E}}(x)}\\right| \\le 1\\) for\nall \\(x\\), and the largest possible value of \\(cos x\\) is 1, we have\n<\/p>\n\n\n\n<p>\n\\[\n\\left|\\frac{1}{(n+1)!}x^{n+1}\\cos{\\tilde{\\mathcal{E}}(x)}\\right| \\le \\frac{1}{(n+1)!}x^{n+1}\n\\]\n<\/p>\n\n\n\n<p>\nThe upper bound of the remainder in the approximation will therefore\nbe \\(\\frac{1}{(n+1)!}x^{n+1}\\). The code to calculate the error starts\non <a href=\"https:\/\/bitbucket.org\/marc_perron\/risc-v\/src\/d348e5ed651e9e02ea85547dccc5459d256a001b\/trig\/trig.S#lines-125\">line 37<\/a> prior to returning.\n<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">COS I Said So<\/h2>\n\n\n\n<p> The <code>__taylor<\/code> function defined previously can be used to approximate the cosine of a given angle. The following RISC-V assembly code implements this approximation: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>__cos:\n        addi            sp, sp, 24\n        sd              ra, 16(sp)\n        sd              a0, 8(sp)\n        sd              a1, 0(sp)\n        fld             fa0, 0(a0)      \/\/ fa0 &lt;- x\n        la              a0, cos_lut\n        fclass.d        a1, fa0\n        andi            a1, a1, 0x18    \/\/ Check for zero\n        beqz            a1, 1f\n        lb              a1, 0(a0)       \/\/ if x = 0; load from lut\n        fcvt.d.l        fa0, a1\n        j               2f\n1:\n        li              a1, 7           \/\/ else; use the 7-th taylor polynomial.\n        call            __taylor\n2:\n        ld              a1, 0(sp)\n        ld              a0, 8(sp)\n        ld              ra, 16(sp)\n        fsd             fa0, 0(a1)\n        ret<\/code><\/pre>\n\n\n\n<p> It&#8217;s important to note that for the simple cases, the Taylor polynomial is not used since the exact value is known. On <a href=\"https:\/\/bitbucket.org\/marc_perron\/risc-v\/src\/d348e5ed651e9e02ea85547dccc5459d256a001b\/trig\/trig.S#lines-26\">line 8<\/a> of the code listing, the <code>fclass.d<\/code> instruction is used to determine whether the class of the double-precision value that was loaded into register <code>fa0<\/code>. If its value is 0, one of bits 3 or 4 of the target register, <code>a1<\/code> in this case, will be asserted indicating that it is either positive or negative zero (which are effectively the same but my have different semantic meanings). <\/p>\n\n\n\n<p> If the angle provided to the <code>__cos<\/code> function is in fact zero, the lookup table will be consulted to find the exact value of the cosine of the angle; the table is referenced by the symbol <code>cos_lut<\/code>. Otherwise the 7-th Taylor polynomial is used to approximate its value. The <code>__taylor<\/code> function is invoked with the address of the <code>cos_lut<\/code> table, the order of the polynomial, and the value of the angle \\(x\\) as its arguments. <\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Conclusion<\/h1>\n\n\n\n<p>\nAlthough the base RISC-V instructions allow for integer arithmetic\nonly, the floating-point extension provides the ability to manipulate\nrational numbers as well. This is useful for carrying out calculations\nfor the real world. However, this still precludes irrational numbers\nwhich are important quantities if, say for example, we wish to\ncalculate the cosine of a given angle.\n<\/p>\n\n\n\n<p>\nA lookup table can be used to determine pre-computed values for\ncertain functions which would otherwise be diffcult to express. In\nfact, many mathematics textbooks include such look-up tables in their\nappenices. However pre-computing values requires knowing which values\nwill need to be computed.\n<\/p>\n\n\n\n<p>\nA better approach is to approximate these values using the Taylor\nseries. However, this increases the time complexity of calculations as\nprecision improves. Therefore it is important that this function be\ncarried out as efficiently as possible.\n<\/p>\n\n\n\n<p>\nIn this article, we looked at a RISC-V assembly implementation of a\nfunction to calculate the Taylor polynomial. This function was used to\napproximate the cosine of an angle \\(x\\), expressed in radians, to some\narbitrary precision. Although only we only looked at \\(cos x\\) the same\nprocedure can also be used to evaluate \\(sin x\\) (using a different\nlookup table). The code for this example is available in a\nBitBucket<sup><a id=\"fnr.4\" class=\"footref\" href=\"#fn.4\">4<\/a><\/sup> repository. This code also implements the \\(sin\\)\nfunction using the same technique.\n<\/p>\n\n\n\n<p>\nThis implementation of the Taylor polynomial can also be re-used to\napproximate any function whose derivatives are periodic. The only\npre-condition is to provide a lookup table to determine the values of\nthe n-th derivative. Play around with the code to see if you can\napproximate other functions, it&#8217;s not as RISC-y as it seems.\n<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Footnotes<\/h3>\n\n\n\n<p><sup><a id=\"fn.1\" href=\"#fnr.1\">1<\/a><\/sup> David Goldberg. 1991. What every computer scientist should know about floating-point arithmetic. ACM Comput. Surv. 23, 1 (March 1991), 5\u201348. <a href=\"https:\/\/doi.org\/10.1145\/103162.103163\">https:\/\/doi.org\/10.1145\/103162.103163<\/a><\/p>\n\n\n\n<p><sup><a id=\"fn.2\" href=\"#fnr.2\">2<\/a><\/sup> <a href=\"https:\/\/web.archive.org\/web\/20180419150129\/http:\/\/grouper.ieee.org\/groups\/754\/\">https:\/\/web.archive.org\/web\/20180419150129\/http:\/\/grouper.ieee.org\/groups\/754\/<\/a><\/p>\n\n\n\n<p><sup><a id=\"fn.3\" href=\"#fnr.3\">3<\/a><\/sup> <a href=\"https:\/\/en.wikipedia.org\/wiki\/Taylor_series\">https:\/\/en.wikipedia.org\/wiki\/Taylor_series<\/a><\/p>\n\n\n\n<p><sup><a id=\"fn.4\" href=\"#fnr.4\">4<\/a><\/sup> <a href=\"https:\/\/bitbucket.org\/marc_perron\/risc-v\/src\/mainline\/\">https:\/\/bitbucket.org\/marc_perron\/risc-v\/src\/mainline\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Rationalism is a sociological philosophy which, in a general sense, eschews the understanding of reality through mystery and magic. This has parallels with computing where results can often seem magical. This is doubly true when dealing with real-world numbers: although the hardware seems ill equipped to express real numerical values complex calculations are nonetheless possible. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-59","post","type-post","status-publish","format-standard","hentry","category-risc-v"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/59","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/comments?post=59"}],"version-history":[{"count":29,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/59\/revisions"}],"predecessor-version":[{"id":91,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/59\/revisions\/91"}],"wp:attachment":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/media?parent=59"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/categories?post=59"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/tags?post=59"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}