{"id":4250,"date":"2020-07-25T00:01:30","date_gmt":"2020-07-25T07:01:30","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=4250"},"modified":"2020-07-25T07:36:51","modified_gmt":"2020-07-25T14:36:51","slug":"my-own-square-root-funtion","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=4250","title":{"rendered":"My Own Square Root Funtion"},"content":{"rendered":"<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2020\/07\/0725-figure1.png\" alt=\"\" width=\"240\" height=\"187\" class=\"alignleft size-full wp-image-4271\" \/> From <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4246\">last week&#8217;s Lesson<\/a>, I plowed into a BASIC programming book I worked on 35 years ago. (Yes, I&#8217;m old.) In it, substitute code was offered for commands not available in every version of BASIC. To appreciate this necessity, understand that back in those days computers weren&#8217;t file-to-file compatible, so translating programming language dialects was part of the job.<br \/>\n<!--more--><br \/>\nThe algorithm presented in the book for calculating a square root was close, but misses the first step in the process: to find the closest known perfect square. This approach is one of many, and the one I selected to craft my own square root function. It&#8217;s based on <a href=\"http:\/\/www.math.com\/school\/subject1\/lessons\/S1U1L9DP.html\" rel=\"noopener noreferrer\" target=\"_blank\">this post<\/a> on the <a href=\"http:\/\/www.math.com\/\" rel=\"noopener noreferrer\" target=\"_blank\">math.com<\/a> website.<\/p>\n<p>Here are the steps for finding the square root of a value, <em>X<\/em>.<\/p>\n<ol>\n<li>Find the nearest perfect square.<\/li>\n<li>Divide the number, <em>n<\/em>, by the nearest perfect square.<\/li>\n<li>Average the result of Step 2 and the perfect square.<\/li>\n<li>If the result of Step 3 squared equals <em>n<\/em>, you&#8217;re done. Otherwise, continue to divide and average.<\/li>\n<\/ol>\n<p>For my function, the first step is to generate perfect squares until you find one close to <em>n<\/em>. For example, to find the square root of 20, you could use 4<sup>2<\/sup> as 16 for the nearest perfect square.<\/p>\n<p>The second step is to divide <em>n<\/em> by the perfect square: <code>20 \/ 4<\/code>, which equals 5.<\/p>\n<p>The third step is to take the value from Step 2 and average it with the perfect square: <code>( 5 + 4 ) \/ 2<\/code>, which equals 4.5.<\/p>\n<p>Fourth, square the result to see how close you are: <code>4.5 * 4.5 = 20.25<\/code>. If this value doesn&#8217;t equal the original value <em>n<\/em> (20), repeat the process using the new square root wannabe value:<\/p>\n<p><code>( 20 \/ 4.5 + 4.5 ) \/ 2 = 4.4722<\/code>, and <code>4.4722<sup>2<\/sup> = 20.00<\/code><\/p>\n<p>According to my calculator, the square root of 20 is 4.4721. The value 4.4722 is close enough. If not, you must repeat the process:<\/p>\n<p><code>( 20 \/ 4.4722 + 4.47225 ) \/ 2 = 4.4721<\/code>, and <code>4.4721<sup>2<\/sup> = 20.00<\/code><\/p>\n<p>Floating point values in C are precise only to a given number of digits. One problem I had was to determine when a wannabe square root values was good enough. My solution is presented in the following code:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2020_07_25-Lesson.c\" rel=\"noopener noreferrer\" target=\"_blank\">2020_07_25-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\ndouble square_root(double x)\r\n{\r\n    double y;\r\n    int p,square,c;\r\n\r\n    <span class=\"comments\">\/* find the surrounding perfect squares *\/<\/span>\r\n    p = 0;\r\n    do\r\n    {\r\n        p++;\r\n        square = (p+1) * (p+1);\r\n    }\r\n    while( x &gt; square );\r\n\r\n    <span class=\"comments\">\/* process the root *\/<\/span>\r\n    y = (double)p;\r\n    c = 0;\r\n    while(c&lt;10)\r\n    {\r\n        <span class=\"comments\">\/* divide and average *\/<\/span>\r\n        y = (x\/y + y)\/2;\r\n        <span class=\"comments\">\/* test for success *\/<\/span>\r\n        if( y*y == x)\r\n            return(y);\r\n        c++;\r\n    }\r\n    return(y);\r\n}\r\n\r\nint main()\r\n{\r\n    double pv,sr;\r\n\r\n    printf(\"Enter a positive value: \");\r\n    scanf(\"%lf\",&amp;pv);\r\n    if( pv &lt;= 0 )\r\n        return(1);\r\n    sr = square_root(pv);\r\n    printf(\"The square root of %.0f is %f\\n\",\r\n            pv,\r\n            sr\r\n          );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The first thing the <em>square_root()<\/em> function does is calculate perfect squares. The <em>do-while<\/em> loop repeats until the square in integer <code>p<\/code> is just under argument <code>x<\/code>.<\/p>\n<p>Second, a loop processes the expression <code>y = (x\/y + y)\/2<\/code>, where <code>y<\/code> is the wannabe square root value and <code>x<\/code> is the value passed to the function. a test is made <code>y*y == x<\/code> to determine whether the root is found. If so the function returns <code>y<\/code>. If not, it loops at most 10 more times to hone the value. It could probably loop fewer or more iterations, but without any way to compare significant digits in a floating point value, I choose 10 times.<\/p>\n<p>As it stands, the code runs and generates values that compare solidly with the computer&#8217;s calculator app. Therefore, I am pleased.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I swear I&#8217;m not a math nerd, yet I felt compelled to write my own square root function. Perhaps I&#8217;m just weird? <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4250\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-4250","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4250","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4250"}],"version-history":[{"count":9,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4250\/revisions"}],"predecessor-version":[{"id":4275,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4250\/revisions\/4275"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4250"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4250"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4250"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}