Last post I promised that my next few posts would kick it up a notch. I won’t let you down…

One thing I like to do to push the limits of my programming knowledge and think outside the box is to create functions that replicate native methods, without using native methods or reserved words to achieve the goal; so strictly operators only.

I’ve taken a rather bold example for my first example here, the calculation of a square root of a number.

The calculation of square roots has been done time and time again over the centuries. One of the well known methods for calculating a square root is called “Newton’s Method”, and its usage extends to the derivation of roots for any polynomial.

The function that governs square root calculation using Newton’s Method is:

*f(x+1) = f(x) – (f(x)² – A)/(2 × f(x))*

Where ** f(x) **is the previous term,

**is the new term, and A is the original number being square-rooted. This is a recursive process, starting with**

*f(x+1)***. Once you start plugging in the values, getting your next term and plugging that in, over and over, you’ll find that the value of**

*f(0) = A***converges slowly to the square root of**

*f(x+1)***. With each iteration, the value of**

*A***gets smaller and smaller until it reaches zero. Put simply, this expression is our “error factor”.**

*(f(x)² – A)/(2 × f(x))*I like this process as it can be readily replicated in JavaScript. Bear in mind first, that my initial draft of the function below is just that, an initial draft. We will be taking a look at its evolution in this post to something more compact.

*z=(x,y)=>*

*((y=y||x)*y-x)/(2*y)>1e-15?*

*z(x,y-(y*y-x)/(2*y)):y*

So what have we done here? Let’s go through step-by-step.

Firstly, this function takes two parameters, with the initial function being called with one parameter, for example, ** z(37) **to get the square root of 37. The reason behind using two parameters is during subsequent iterations of the function it calls two parameters,

**, the value of the original number being passed, and**

*x***, a number getting closer to the square root of**

*y***with each iteration**

*x*

*.*Recursion is one of the only few ways to perform this algorithm because you’re essentially performing the same process over and over until a certain amount of acceptable accuracy is reached. Depending on the value of ** x** passed through one could potentially get a

*“Maximum Call Stack Size Exceeded”*error from all the nested loops caused by said recursion.

Given the upper bound limits within JavaScript, my testing has shown that this starts losing cohesion at about ** z(1E140)**, i.e. the square root of 1 followed by 140 zeroes… We should potentially see an answer of

**“1e+70”**, but what we do end up getting is

**. Given the limit of available decimal places this ain’t bad, but what are the chances that you’ll be playing with numbers that large? By comparison, with reference to MarketWatch.com, as of September 15, this year, the US national debt stands at just over 20 trillion (20E+12) dollars [source], but I digress.**

*9.999999999999999e+69*Remember when I mentioned that the value of ** f(0) **was

**, our initial parameter being passed when starting the Newton’s Method algorithm? This is being implemented in the initial part of our function as**

*A***. This ensures that when we kick off the first iteration of**

*(y=y||x)***, that we have a value for**

*z***to play with by defaulting to our original number, and taking on the available value of**

*y***in subsequent iterations.**

*y*Next, as it can be seen, we’re using a ternary operator here, this is the ** ?:** operator. Ternary operators are pretty damn cool in my opinion. They’re basically a shortcut way of expressing an

**if-then-else**statement. They take on the form

**. If condition**

*_condition?_if_true:_if_false***is met, then the statement**

*_condition***prevails, else the statement**

*_if_true***prevails. For example, with**

*_if_false***if the age passed is 18 or over, the returned value is**

*age>=18?”Can vote”:”Cannot vote”***, otherwise the returned value becomes**

*“Can vote”***.**

*“Cannot vote”*In this case we’re comparing the value of ** ((y=y||x)*y-x)/(2*y)** with 1e-15, or 0.000000000000001… Tiny number. So we’re simply seeing how low our error factor is. Bear in mind, I had actually been using this to determine

**when I was initially testing this, so an error of 1e-15 seemed like a good idea at the time especially considering I compared it to the value of**

*z(37)***. I then later realized I needed to reduce it down to practically zero, but we’ll address that later in this post.**

*Math.sqrt(37)*If the ternary condition is true, i.e. the error factor is still to large to be deemed acceptable, the function runs another iteration of itself, but passes ** x **as well as

**minus the error factor, thereby getting closer to the original answer, and thereby reducing the error factor closer to zero. If the error factor is deemed sufficiently low, it returns the value of**

*y***, our square root.**

*y*Let’s reduce it further… As ES6 allows parameters to take on defaults we can shift the default short circuit of ** (y=y||x)** and place it within the parameter component of our function. Now it becomes:

*z=(x,y=x)=>*

*(y=(y*y-x)/(2*y))>1e-15?*

*z(x,y-(y*y-x)/(2*y)):y*

Notice now we have two instances of ** (y*y-x)/(2*y)**, so let’s introduce a new variable

**which will act as a marker, taking on**

*k***as a default and also take advantage of the fact that if you reduce a number small enough in JavaScript that it will coerce that number to zero… This is a phenomenon that’s known as zero underflow. This is where the number gets so small the JavaScript compiler throws up its hands and goes “You know what? That’s close enough to zero for me, I’m gonna call it zero” and runs with it… As a result, you get this:**

*x**z=(x,y=k=x)=>*

*(k/=2)?z(x,y-(y*y-x)/(2*y)):y*

We’re using a divisor of 2 here so we can get as many iterations as possible and it also links nicely with our divisor in our second parameter in the recursed call. We can narrow this further. Let’s take a look at that second parameter in the recursive call: ** y-(y*y-x)/(2*y)**. A bit messy, but some simple algebra and a little JavaScript shortcutting can shorten this up.

*y-(y*y-x)/(2*y)*

Let’s rewrite this in algebraic form for ease of manipulation…

*y – (y² – x)/2y*

Let’s expand this, remembering that if you’re subtracting a negative, you’re actually adding a positive…

*2y²/2y – y²/2y + x/2y*

Which narrows down to:

*y²/2y + x/2y*

Which, in turn, narrows down to:

*y/2 + x/2y*

Which can also be expressed as:

*y/2+x/2/y*

Which can then be thrust back into our function:

*z=(x,y=k=x)=>(k/=2)?z(x,y/2+x/2/y):y*

Pretty sleek if you ask me… As you can see, this has taken away our need for an accuracy check as each iteration will persist until we hit that zero underflow I talked about earlier, which by that stage ** y** will have reached a close enough value to the square root of

**.**

*x*One final caveat here, this function doesn’t take into account negative numbers, +Infinity, NaN (not a number) values or any number that’s ridiculously high that is close to +Infinity. I’ll revisit tidying this function up later on.

We’ll be taking advantage of this function in a later post where we use this to derive another alternate version of another JavaScript method. More on that later. Next post will be used to focus on the derivation of the three main trigonometric functions in a similar fashion as above.

Before I sign off for today, I wanted to thank a fellow code golfer, Arnauld, for his insight of taking advantage of zero underflow to golf this down; it was much appreciated.

Until the next post!