Back

C

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  stdio.h provides the "printf" function, used for printing text.           */
#include <stdio.h>

/*  Floating-point absolute value function, fabs, provided here.              */
#include <math.h>

/*  Computes the square root of a positive real number via Heron's method.    */
static double herons_method(double x)
{
    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      *
     *                                                                        *
     *  Note:                                                                 *
     *      We are declaring the following integer as "unsigned" meaning      *
     *      non-negative. The "U" after the number is the suffix for unsigned *
     *      constants in C. It simply means unsigned.                         */
    const unsigned int maximum_number_of_iterations = 16U;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const double epsilon = 8.881784197001252E-16;

    /*  Variable for keeping track of how many iterations we have performed.  */
    unsigned int iters;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    double approximate_root = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters = 0; iters < maximum_number_of_iterations; ++iters)
    {
        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        const double error = (x - approximate_root * approximate_root) / x;

        if (fabs(error) <= epsilon)
            break;

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximate_root = 0.5 * (approximate_root + x / approximate_root);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase maximum_number_of_iterations.      */
    return approximate_root;
}
/*  End of herons_method.                                                     */

/*  Main routine used for testing our implementation of Heron's method.       */
int main(void)
{
    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const double x = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    const double sqrt_x = herons_method(x);
    printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);

    return 0;
}

/*  We can execute this on GNU, Linux, FreeBSD, macOS, etc., via:             *
 *      cc herons_method.c -o main                                            *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows you will need to install a C compiler. Common options are      *
 *  Microsoft's MSVC, LLVM's clang, MinGW (which uses the GNU toolchain),     *
 *  or installing Cygwin and running the commands above. Using MSVC, type:    *
 *      cl herons_method.c /link /out:main.exe                                *
 *      main.exe                                                              *
 *  This will produce the same output.                                        */

C3

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/05/25                                                        *
 ******************************************************************************/

/*  std::io provides the "printfn" function, used for printing text.          */
import std::io;

/*  Floating-point absolute value function, abs, provided here.               */
import std::math;

/*  Computes the square root of a positive real number via Heron's method.    */
fn double herons_method(double x)
{
    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const uint MAXIMUM_NUMBER_OF_ITERATIONS = 16U;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const double EPSILON = 8.881784197001252E-16;

    /*  Variable for keeping track of how many iterations we've performed.    */
    uint iters;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    double approximate_root = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters = 0; iters < MAXIMUM_NUMBER_OF_ITERATIONS; ++iters)
    {
        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        double error = (x - approximate_root * approximate_root) / x;

        if (math::abs(error) <= EPSILON) {
            break;
        }

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximate_root = 0.5 * (approximate_root + x / approximate_root);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase MAXIMUM_NUMBER_OF_ITERATIONS.      */
    return approximate_root;
}
/*  End of herons_method.                                                     */

/*  Main routine used for testing our implementation of Heron's method.       */
fn void main()
{
    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const double X = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    double sqrt_X = herons_method(X);
    io::printfn("sqrt(%.1f) = %.16f", X, sqrt_X);
}

/*  We can execute this on GNU, Linux, FreeBSD, macOS, Windows, etc., by      *
 *  downloading the official C3 compiler, c3c:                                *
 *      https://c3-lang.org/getting-started/prebuilt-binaries/                *
 *  Once installed you can compile and run on Windows by typing:              *
 *      c3c compile herons_method.c3 -o main.exe                              *
 *      main.exe                                                              *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On every other platform you can do something similar:                     *
 *      c3c compile herons_method.c3 -o main                                  *
 *      ./main                                                                *
 *  This will produce the same output.                                        */

C++

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  stdio provides the "printf" function, used for printing text.             */
#include <cstdio>

/*  Floating-point absolute value function, fabs, provided here.              */
#include <cmath>

/*  Class providing an implementation of sqrt using Heron's method.           */
class Heron {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      *
     *                                                                        *
     *  Note:                                                                 *
     *      We are declaring the following integer as "unsigned" meaning      *
     *      non-negative. The "U" after the number is the suffix for unsigned *
     *      constants in C++. It simply means unsigned.                       */
    static const unsigned int maximum_number_of_iterations = 16U;

    /*  We want the function visible outside the class. Declare it public.    */
    public:

        /*  Computes square roots of positive real numbers via Heron's method.*
         *  We are declaring this inside of the Heron class, so there should  *
         *  be no naming conflict with std::sqrt, the standard square root.   */
        static double sqrt(double x)
        {
            /*  Maximum allowed error. This is 4x double precision epsilon.   */
            const double epsilon = 8.881784197001252E-16;

            /*  Variable for keeping track of the number of iterations.       */
            unsigned int iters;

            /*  Set the initial guess to the input. Provided x is positive,   *
             *  Heron's method will indeed converge.                          */
            double approximate_root = x;

            /*  Iteratively loop through and obtain better approximations.    */
            for (iters = 0; iters < maximum_number_of_iterations; ++iters)
            {
                /*  If we are within epsilon of the correct value we may      *
                 *  break out of this for-loop. Check the relative error.     */
                const double error = (x - approximate_root*approximate_root)/x;

                if (std::fabs(error) <= epsilon)
                    break;

                /*  Apply Heron's method to get a better approximation.       */
                approximate_root = 0.5*(approximate_root + x/approximate_root);
            }

            /*  As long as x is positive and not very large, we should have a *
             *  very good approximation for sqrt(x). Heron's method will      *
             *  still work for very large x, but we must increase the value   *
             *  of maximum_number_of_iterations.                              */
            return approximate_root;
        }
        /*  End of sqrt.                                                      */
};
/*  End of Heron definition.                                                  */

/*  Main routine used for testing our implementation of Heron's method.       */
int main(void)
{
    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const double x = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    const double sqrt_x = Heron::sqrt(x);
    std::printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);

    return 0;
}

/*  We can execute this on GNU, Linux, FreeBSD, macOS, etc., via:             *
 *      c++ herons_method.cpp -o main                                         *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows you will need to install a C++ compiler. Microsoft's MSVC is a *
 *  common option. Using MSVC, type:                                          *
 *      cl herons_method.cpp /link /out:main.exe                              *
 *      main.exe                                                              *
 *  This will produce the same output.                                        */

C#

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  Console.WriteLine and Math.Abs are both provided here.                    */
using System;

/*  Class providing an implementation of Heron's method.                      */
class Heron {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      *
     *                                                                        *
     *  Note:                                                                 *
     *      We are declaring the following integer as "unsigned" meaning      *
     *      non-negative. The "U" after the number is the suffix for unsigned *
     *      constants in C#. It simply means unsigned.                        */
    const uint maximumNumberOfIterations = 16U;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const double epsilon = 8.881784197001252E-16;

    /*  Computes square roots using Heron's method.                           */
    static double HeronsMethod(double x)
    {
        /*  Dummy variable for keeping track of the number of iterations.     */
        uint iters;

        /*  Initial approximation for Heron's method. Choose the input.       */
        double approximateRoot = x;

        /*  Loop through and iteratively apply Heron's method.                */
        for (iters = 0; iters < maximumNumberOfIterations; ++iters)
        {
            /*  If we are within epsilon of the correct value we may break    *
             *  break out of this for-loop. Check for this.                   */
            double error = (x - approximateRoot * approximateRoot) / x;

            if (Math.Abs(error) < epsilon)
                break;

            /*  Otherwise, improve our approximation using Heron's method.    */
            approximateRoot = 0.5 * (approximateRoot + x / approximateRoot);
        }

        /*  Provided x is positive and not very large, we should have an      *
         *  excellent approximation for sqrt(x). Heron's method does indeed   *
         *  work for large x, but we may need to increase the value of        *
         *  maximumNumberOfIterations.                                        */
        return approximateRoot;
    }
    /*  End of HeronsMethod.                                                  */

    /*  Routine for testing our implementation of Heron's method.             */
    static void Main()
    {
        /*  Compute sqrt(2) using Heron's method and print the result.        */
        double x = 2.0;
        double sqrtX = HeronsMethod(x);
        Console.WriteLine($"sqrt({x}) = {sqrtX}");
    }
}

/*  On Windows you can use Microsoft's C# compiler. Type:                     *
 *      csc herons_method.cs -out:main.exe                                    *
 *      main.exe                                                              *
 *  This will output:                                                         *
 *      sqrt(2) = 1.41421356237309                                            *
 *  This has a relative error of 3.611212654972683e-15. Note, csc only prints *
 *  a double to 15 decimals, the last digit is rounded.                       *
 *                                                                            *
 *  On GNU, Linux, FreeBSD, macOS, etc., you can use the mono C# compiler:    *
 *      mcs herons_method.cs -out:main                                        *
 *      ./main                                                                *
 *  This produces the same result.                                            */

D

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  Computes the square root of a positive real number via Heron's method.    */
static double herons_method(double x)
pure nothrow @safe @nogc
{
    /*  We'll use the absolute value function to compute the relative error.  */
    import std.math : fabs;

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const uint maximum_number_of_iterations = 16U;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const double epsilon = 8.881784197001252E-16;

    /*  Variable for keeping track of how many iterations we have performed.  */
    uint iters;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    double approximate_root = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters = 0; iters < maximum_number_of_iterations; ++iters)
    {
        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        const double error = (x - approximate_root * approximate_root) / x;

        if (fabs(error) <= epsilon)
            break;

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximate_root = 0.5 * (approximate_root + x / approximate_root);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase maximum_number_of_iterations.      */
    return approximate_root;
}
/*  End of herons_method.                                                     */

/*  Main routine used for testing our implementation of Heron's method.       */
int main()
{
    /*  stdio provides the "printf" function, used for printing text.         */
    import std.stdio : printf;

    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const double x = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    const double sqrt_x = herons_method(x);
    printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);

    return 0;
}

/*  We can run this on GNU, Linux, FreeBSD, etc., using the GNU D compiler,   *
 *  which is part of the GNU Compiler Collection (GCC), via:                  *
 *      gdc herons_method.d -o main                                           *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On macOS and Windows you can install the official D compiler, DMD:        *
 *      https://dlang.org/download.html                                       *
 *  Once installed you can compile and run on Windows by typing:              *
 *      dmd herons_method.d -of=main.exe                                      *
 *      main.exe                                                              *
 *  On macOS you can do something similar:                                    *
 *      dmd herons_method.d -of=main                                          *
 *      ./main                                                                *
 *  These will produce the same output.                                       */

Fortran

!------------------------------------------------------------------------------!
!                                   LICENSE                                    !
!------------------------------------------------------------------------------!
!   This file is part of mitx_mathematics_programming_examples.                !
!                                                                              !
!   mitx_mathematics_programming_examples is free software: you can            !
!   redistribute it and/or modify it under the terms of the GNU General Public !
!   License as published by the Free Software Foundation, either version 3 of  !
!   the License, or (at your option) any later version.                        !
!                                                                              !
!   mitx_mathematics_programming_examples is distributed in the hope that it   !
!   will be useful but WITHOUT ANY WARRANTY; without even the implied warranty !
!   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           !
!   GNU General Public License for more details.                               !
!                                                                              !
!   You should have received a copy of the GNU General Public License          !
!   along with mitx_mathematics_programming_examples.  If not, see             !
!   <https://www.gnu.org/licenses/>.                                           !
!------------------------------------------------------------------------------!
!   Purpose:                                                                   !
!       Calculates square roots using Heron's method.                          !
!------------------------------------------------------------------------------!
!   Author: Ryan Maguire                                                       !
!   Date:   2025/03/08                                                         !
!------------------------------------------------------------------------------!
MODULE HERON

    IMPLICIT NONE

    ! Heron's method is iterative. The convergence is quadratic, meaning the
    ! number of accurate decimals doubles with each iteration. Because of this
    ! we can halt the algorithm after a few steps.
    INTEGER :: MAXIMUM_NUMBER_OF_ITERATIONS = 16

    ! Maximum allowed error. This is 4x double precision epsilon.
    REAL :: EPSILON = 8.881784197001252E-16

    CONTAINS

    !--------------------------------------------------------------------------!
    !   Function:                                                              !
    !       HERONS_METHOD                                                      !
    !   Purpose:                                                               !
    !       Computes square roots using Heron's method.                        !
    !   Arguments:                                                             !
    !       X (REAL):                                                          !
    !           A positive real number.                                        !
    !   OUTPUT:                                                                !
    !       SQRT_X (REAL):                                                     !
    !           The square root of X.                                          !
    !--------------------------------------------------------------------------!
    FUNCTION HERONS_METHOD(X)

        IMPLICIT NONE

        ! The input is a positive real number.
        REAL, INTENT(IN) :: X

        ! The output is also a positive real number, the square root of X.
        REAL :: HERONS_METHOD

        ! Dummy variable for keeping track of how many iterations we've done.
        INTEGER :: ITERS

        ! Variable used for Heron's approximation. We will iteratively update
        ! this value with better approximations using Heron's method.
        REAL :: APPROXIMATE_ROOT

        ! Variable for tracking the relative error. When this is very small
        ! (less than epsilon) we will break out of the loop and return.
        REAL :: ERROR

        ! Heron's method needs a starting value. Initialize this to the input.
        APPROXIMATE_ROOT = X

        ! Iteratively perform Heron's method.
        DO ITERS = 0, MAXIMUM_NUMBER_OF_ITERATIONS

            ! If the error is small we can break out of this loop.
            ERROR = (X - APPROXIMATE_ROOT * APPROXIMATE_ROOT) / X

            IF (ABS(ERROR) .LT. EPSILON) THEN
                EXIT
            END IF

            ! Otherwise, improve our approximation using Heron's method.
            APPROXIMATE_ROOT = 0.5 * (APPROXIMATE_ROOT + X / APPROXIMATE_ROOT)
        END DO

        ! If x is positive and not too big, APPROXIMATE_ROOT should have a
        ! very accurate approximation to sqrt(x). Heron's method works for
        ! large inputs as well, but we need to increase the value of
        ! MAXIMUM_NUMBER_OF_ITERATIONS.
        HERONS_METHOD = APPROXIMATE_ROOT
    END FUNCTION HERONS_METHOD
END MODULE HERON

! Program for testing our implementation of Heron's method.
PROGRAM MAIN

    USE HERON
    IMPLICIT NONE

    ! The input for the method. We'll compute sqrt(2).
    REAL :: X = 2.0

    ! Variable for the output.
    REAL :: SQRT_X

    ! Run the routine, computing sqrt(x), and print the result.
    SQRT_X = HERONS_METHOD(X)
    PRINT "(A,F3.1,A,F18.16)", "SQRT(", X, ") = ", SQRT_X

END PROGRAM MAIN

! You can compile this on GNU, Linux, FreeBSD, macOS, etc., using
! GNU's Fortran compiler, gfortran. Type:
!   gfortran -fdefault-real-8 herons_method.f90 -o main
!   ./main
! This will output:
!   SQRT(2.0) = 1.4142135623730949
! This has a relative error of 1.570092458683775E-16.
!
! On Windows you can also use gfortran by installing MSYS2:
!   https://www.msys2.org/
! Along with mingw-w64:
!   https://www.mingw-w64.org/getting-started/msys2/
! Once gfortan is installed, you can type:
!   gfortran -fdefault-real-8 herons_method.f90 -o main.exe
!   main.exe
! This will produce the same output.

Go

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/
package main

/*  Only standard library imports are needed.                                 */
import (
    "fmt"   /*  Printf provided here, used for printing text to the screen.   */
    "math"  /*  Abs, floating-point absolute value function, found here.      */
)

/*  Computes the square root of a positive real number via Heron's method.    */
func herons_method(x float64) float64 {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const maximum_number_of_iterations uint32 = 16

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const epsilon float64 = 8.881784197001252E-16

    /*  Variable for keeping track of how many iterations we have performed.  */
    var iters uint32

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    var approximate_root = x

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for iters = 0; iters < maximum_number_of_iterations; iters += 1 {

        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        var error = (x - approximate_root * approximate_root) / x

        if math.Abs(error) <= epsilon {
            break
        }

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximate_root = 0.5 * (approximate_root + x / approximate_root)
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase maximum_number_of_iterations.      */
    return approximate_root
}
/*  End of herons_method.                                                     */

/*  Main routine used for testing our implementation of Heron's method.       */
func main() {

    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const x float64 = 2.0

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    var sqrt_x = herons_method(x)
    fmt.Printf("sqrt(%.1f) = %.16f\n", x, sqrt_x)
}

/*  We can run this on GNU, Linux, FreeBSD, etc., using the GNU Go compiler,  *
 *  which is part of the GNU Compiler Collection (GCC), via:                  *
 *      gccgo herons_method.go -o main                                        *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On macOS and Windows you can install Google's official Go compiler:       *
 *      https://go.dev/                                                       *
 *  Once installed you can compile and run by typing:                         *
 *      go run herons_method.go                                               *
 *  This will produce the same output.                                        */

Java

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  Implementation of sqrt using Heron's method.                              */
final public class Heron {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    static private final int maximum_number_of_iterations = 16;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    static private final double epsilon = 8.881784197001252E-16;

    /*  Function for computing the square root of a positive real number      *
     *  using Heron's method.                                                 */
    static private double heronsMethod(double x)
    {
        /*  Dummy variable for keeping track of the number of iterations.     */
        int iters;

        /*  Starting value for Heron's method. The input will suffice.        */
        double approximate_root = x;

        /*  Loop through and iteratively perform Heron's method.              */
        for (iters = 0; iters < maximum_number_of_iterations; ++iters)
        {
            /*  If the error is small enough we can break out of the loop. We *
             *  want small relative error, so compute this.                   */
            final double error = (x - approximate_root * approximate_root) / x;

            if (Math.abs(error) <= epsilon)
                break;

            /*  Otherwise improve the error by applying Heron's method.       */
            approximate_root = 0.5 * (approximate_root + x / approximate_root);
        }

        /*  As long as x is positive and not very large, we should have a     *
         *  very good approximation for sqrt(x). Heron's method works for     *
         *  large x, but we may need to increase maximum_number_of_iterations.*/
        return approximate_root;
    }

    /*  Main routine for testing our implementation of Heron's method.        */
    static public void main(String[] args)
    {
        /*  Test out Heron's method by computing sqrt(2).                     */
        final double x = 2.0;
        final double sqrt_x = Heron.heronsMethod(x);
        System.out.printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);
    }
}

/*  We can execute this on GNU, Linux, FreeBSD, macOS, Windows, etc., using   *
 *  OpenJDK. After installing, type:                                          *
 *      java herons_method.java                                               *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730950                                        *
 *  This has a relative error of 1.570092458683775E-16.                       */

Julia

################################################################################
#                                   LICENSE                                    #
################################################################################
#   This file is part of mitx_mathematics_programming_examples.                #
#                                                                              #
#   mitx_mathematics_programming_examples is free software: you can            #
#   redistribute it and/or modify it under the terms of the GNU General Public #
#   License as published by the Free Software Foundation, either version 3 of  #
#   the License, or (at your option) any later version.                        #
#                                                                              #
#   mitx_mathematics_programming_examples is distributed in the hope that it   #
#   will be useful, but WITHOUT ANY WARRANTY; without even the implied         #
#   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  #
#   GNU General Public License for more details.                               #
#                                                                              #
#   You should have received a copy of the GNU General Public License          #
#   along with mitx_mathematics_programming_examples.  If not, see             #
#   <https://www.gnu.org/licenses/>.                                           #
################################################################################
#   Purpose:                                                                   #
#       Calculates square roots using Heron's method.                          #
################################################################################
#   Author:     Ryan Maguire                                                   #
#   Date:       March 9, 2025.                                                 #
################################################################################

################################################################################
#   Function:                                                                  #
#       herons_method                                                          #
#   Purpose:                                                                   #
#       Computes square roots of positive real numbers using Heron's method.   #
#   Arguments:                                                                 #
#       x (real):                                                              #
#           A positive real number, the input to the square root function.     #
#   Output:                                                                    #
#       sqrt_x (real):                                                         #
#           The square root of the input.                                      #
################################################################################
function herons_method(x)

    # Heron's method is iterative and the convergence is quadratic. This
    # means that if a_{n} has N correct decimals, then a_{n+1} will have
    # 2N correct decimals. A standard 64-bit double can fit about 16
    # decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).
    # Because of this we may exit the function after a few iterations.
    maximum_number_of_iterations = 16

    # The maximum allowed error. This is 4x double precision epsilon.
    epsilon = 8.881784197001252E-16

    # Set the initial guess to the input. Provided x is positive, Heron's
    # method will indeed converge.
    approximate_root = x

    # Iteratively apply Heron's method.
    for _ = 1:maximum_number_of_iterations

        # If the error is small we can break out of this for-loop. Check.
        error = (x - approximate_root * approximate_root) / x

        if abs(error) <= epsilon
            break
        end

        # Otherwise improve the approximation using Heron's method.
        approximate_root = 0.5 * (approximate_root + x / approximate_root)

    end

    # As long as x is positive and not very large, we should have a very
    # good approximation for sqrt(x). Heron's method will still work for
    # very large x, but we must increase maximum_number_of_iterations.
    return approximate_root

end

# Test out our implementation by computing the square root of 2.
x = 2.0
sqrt_x = herons_method(x)
println("sqrt(", x, ") = ", sqrt_x)

# We can run this on GNU, Linux, FreeBSD, macOS, Windows, etc.
# First install Julia:
#   https://julialang.org/downloads/
# Once installed, type:
#   julia herons_method.jl
# This will output:
#   sqrt(2.0) = 1.414213562373095
# This has a relative error of 1.570092458683775E-16.

JavaScript

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/05/18                                                        *
 ******************************************************************************/

/*  Computes the square root of a positive real number via Heron's method.    */
function heronsMethod(x) {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const MAXIMUM_NUMBER_OF_ITERATIONS = 16;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    const EPSILON = 8.881784197001252E-16;

    /*  Variable for keeping track of how many iterations we have performed.  */
    let iters;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    let approximateRoot = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters = 0; iters < MAXIMUM_NUMBER_OF_ITERATIONS; ++iters) {

        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        const error = (x - approximateRoot * approximateRoot) / x;

        if (Math.abs(error) <= EPSILON) {
            break;
        }

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximateRoot = 0.5 * (approximateRoot + x / approximateRoot);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase MAXIMUM_NUMBER_OF_ITERATIONS.      */
    return approximateRoot;
}
/*  End of heronsMethod.                                                      */

/*  Test out our function, compute sqrt(2) and print it to the screen.        */
const X = 2.0;
const SQRT_2 = heronsMethod(X);
console.log("sqrt(2) = " + SQRT_2.toFixed(16));

/*  We can run this outside of a browser by using the cross-platform runtime  *
 *  environment node.js:                                                      *
 *      https://nodejs.org/en                                                 *
 *  After installing, type:                                                   *
 *      node herons_method.js                                                 *
 *  This will output:                                                         *
 *      sqrt(2) = 1.4142135623730949                                          *
 *  This has a relative error of 1.570092458683775E-16.                       */

Kotlin

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/05/18                                                        *
 ******************************************************************************/
import kotlin.math.abs

/******************************************************************************
 *  Function:                                                                 *
 *      heronsMethod                                                          *
 *  Purpose:                                                                  *
 *      Computes square roots of positive real numbers using Heron's method.  *
 *  Arguments:                                                                *
 *      x (Double):                                                           *
 *          A positive real number, the input to the square root function.    *
 *  Output:                                                                   *
 *      sqrt_x (Double):                                                      *
 *          The square root of the input.                                     *
 ******************************************************************************/
fun heronsMethod(x: Double): Double {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    val maximumNumberOfIterations: Int = 16

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    val epsilon: Double = 8.881784197001252E-16

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    var approximateRoot: Double = x

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters in 0 .. maximumNumberOfIterations) {

        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        val error: Double = (x - approximateRoot * approximateRoot) / x

        if (abs(error) <= epsilon)
            break

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximateRoot = 0.5 * (approximateRoot + x / approximateRoot)
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase maximum_number_of_iterations.      */
    return approximateRoot
}
/*  End of heronsMethod.                                                      */

/*  Test out our function, compute the square root of 2.                      */
fun main() {
    val x = 2.0
    val sqrt_x = heronsMethod(x)
    println("sqrt($x) = $sqrt_x")
}

/*  We can run this using the Kotlin compiler, kotlinc:                       *
 *      https://github.com/JetBrains/kotlin/releases                          *
 *  See also:                                                                 *
 *      https://kotlinlang.org/                                               *
 *  You will also need to install Java OpenJDK. Once done, type:              *
 *      kotlinc herons_method.kt -d herons_method.jar                         *
 *      java -jar herons_method.jar                                           *
 *  This will output:                                                         *
 *      sqrt(2.0) = 1.414213562373095                                         *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows you can install kotlinc-native from the same link. Type:       *
 *      kotlinc-native herons_method.kt -output main.exe                      *
 *      main.exe                                                              *
 *  This produces the same output.                                            */

MATLAB

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                   LICENSE                                    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This file is part of mitx_mathematics_programming_examples.                %
%                                                                              %
%   mitx_mathematics_programming_examples is free software: you can            %
%   redistribute it and/or modify it under the terms of the GNU General Public %
%   License as published by the Free Software Foundation, either version 3 of  %
%   the License, or (at your option) any later version.                        %
%                                                                              %
%   mitx_mathematics_programming_examples is distributed in the hope that it   %
%   will be useful, but WITHOUT ANY WARRANTY; without even the implied         %
%   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  %
%   GNU General Public License for more details.                               %
%                                                                              %
%   You should have received a copy of the GNU General Public License          %
%   along with mitx_mathematics_programming_examples.  If not, see             %
%   <https://www.gnu.org/licenses/>.                                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Purpose:                                                                   %
%       Calculates square roots using Heron's method.                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Author:     Ryan Maguire                                                   %
%   Date:       March 9, 2025.                                                 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Function:                                                                  %
%       herons_method                                                          %
%   Purpose:                                                                   %
%       Computes square roots of positive real numbers using Heron's method.   %
%   Arguments:                                                                 %
%       x (real):                                                              %
%           A positive real number, the input to the square root function.     %
%   Output:                                                                    %
%       sqrt_x (real):                                                         %
%           The square root of the input.                                      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function approximate_root = herons_method(x)

    % Heron's method is iterative and the convergence is quadratic. This
    % means that if a_{n} has N correct decimals, then a_{n+1} will have
    % 2N correct decimals. A standard 64-bit double can fit about 16
    % decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).
    % Because of this we may exit the function after a few iterations.
    maximum_number_of_iterations = 16;

    % The maximum allowed error. This is 4x double precision epsilon.
    epsilon = 8.881784197001252E-16;

    % Set the initial guess to the input. Provided x is positive, Heron's
    % method will indeed converge.
    approximate_root = x;

    % Iteratively apply Heron's method.
    for _ = 1:maximum_number_of_iterations

        % If the error is small we can break out of this for-loop. Check.
        error = (x - approximate_root * approximate_root) / x;

        if abs(error) <= epsilon
            break;
        end

        % Otherwise improve the approximation using Heron's method.
        approximate_root = 0.5 * (approximate_root + x / approximate_root);

    end

end

% Test out our implementation by computing the square root of 2.
x = 2.0;
sqrt_x = herons_method(x);
printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);

% We can run this using GNU Octave, a free and open source
% alternative to MATLAB:
%   https://octave.org/download
% Once installed, type:
%   octave herons_method.matlab.m
% This outputs:
%   sqrt(2.0) = 1.4142135623730949
% This has a relative error of 1.570092458683775E-16.

Objective-C

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  stdio.h provides the "printf" function, used for printing text.           */
#include <stdio.h>

/*  Floating-point absolute value function, fabs, provided here.              */
#include <math.h>

/*  NSObject, the base class for all Objective-C classes, found here.         */
#import <Foundation/Foundation.h>

/*  Simple class with a single method, square root via Heron's method.        */
@interface Heron: NSObject
    + (double) sqrt: (double)x;
@end

/*  Class providing an implementation of sqrt using Heron's method.           */
@implementation Heron

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      *
     *                                                                        *
     *  Note:                                                                 *
     *      We are declaring the following integer as "unsigned" meaning      *
     *      non-negative. The "U" after the number is the suffix for unsigned *
     *      constants in Objective-C. It simply means unsigned.               */
    static const unsigned int maximum_number_of_iterations = 16U;

    /*  The maximum allowed error. This is 4x double precision epsilon.       */
    static const double epsilon = 8.881784197001252E-16;

    /*  Computes square roots of positive real numbers via Heron's method.    */
    + (double) sqrt: (double)x
    {
        /*  Variable for keeping track of the number of iterations.           */
        unsigned int iters;

        /*  Set the initial guess to the input. Provided x is positive,       *
         *  Heron's method will indeed converge.                              */
        double approximate_root = x;

        /*  Iteratively loop through and obtain better approximations.        */
        for (iters = 0; iters < maximum_number_of_iterations; ++iters)
        {
            /*  If we are within epsilon of the correct value we may break    *
             *  out of this for-loop. Check the relative error.               */
            const double error = (x - approximate_root * approximate_root) / x;

            if (fabs(error) <= epsilon)
                break;

            /*  Apply Heron's method to get a better approximation.           */
            approximate_root = 0.5 * (approximate_root + x/approximate_root);
        }

        /*  As long as x is positive and not very large, we should have a     *
         *  very good approximation for sqrt(x). Heron's method will still    *
         *  work for very large x, but we must increase the value of          *
         *  maximum_number_of_iterations.                                     */
        return approximate_root;
    }
    /*  End of sqrt.                                                          */
@end
/*  End of Heron definition.                                                  */

/*  Main routine used for testing our implementation of Heron's method.       */
int main(void)
{
    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    const double x = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    const double sqrt_x = [Heron sqrt: x];
    printf("sqrt(%.1f) = %.16f\n", x, sqrt_x);

    return 0;
}

/*  We can run this by installing GCC, which contains an Objective-C          *
 *  compiler, and GNUstep, which provides the Foundation framework:           *
 *      https://www.gnustep.org/                                              *
 *  Once installed, type:                                                     *
 *      gcc `gnustep-config --objc-flags` herons_method.objc.m -o main \      *
 *          `gnustep-config --objc-libs` `gnustep-config --base-libs`         *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows this is a bit more complicated. Setup MSYS2 and MinGW-w64:     *
 *      https://www.msys2.org/                                                *
 *      https://www.mingw-w64.org/getting-started/msys2/                      *
 *  Then follow the steps to install GCC and GNUstep:                         *
 *      https://mediawiki.gnustep.org/index.php/Installation_MSYS2            *
 *  Once installed, make sure the GNUstep Tools directory is in your DLL path *
 *  and then type:                                                            *
 *      gcc -IC:\msys64\mingw64\Local\Library\Headers   ^                     *
 *          -LC:\msys64\mingw64\Local\Library\Libraries ^                     *
 *          herons_method.objc.m -o main.exe -lobjc -lgnustep-base            *
 *      main.exe                                                              *
 *  This will produce the same result. Windows users can also try using the   *
 *  GNUstep Windows MSVC Toolschain:                                          *
 *      https://github.com/gnustep/tools-windows-msvc                         *
 *  Once installed you can compile Objective-C code from the command line.    */

Pascal

(******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General Public*
 *  License as published by the Free Software Foundation, either version 3 of *
 *  the License, or (at your option) any later version.                       *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that it  *
 *  will be useful but WITHOUT ANY WARRANTY; without even the implied warranty*
 *  of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                              *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples.  If not, see            *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/09                                                        *
 ******************************************************************************)
PROGRAM Heron;

(*  We define two constants: The allowed tolerance (or epsilon value),        *
 *  and the maximum number of iterations we allow for Heron's method.         *)
CONST

    (*  Heron's method is iterative. The convergence is quadratic,            *
     *  meaning the number of accurate decimals doubles with each             *
     *  iteration. Because of this we can stop after a few steps.             *)
    MaximumNumberOfIterations: Integer = 16;

    (*  Maximum allowed error. This is double precision epsilon.              *)
    Epsilon: Real = 2.220446049250313E-16;

    (*  The input value we will compute the square root of.                   *)
    Value: Real = 2.0;

VAR
    (*  Variable for the square root of our input.                            *)
    SqrtValue: Real;

(******************************************************************************
 *  Function:                                                                 *
 *      HeronsMethod                                                          *
 *  Purpose:                                                                  *
 *      Computes square roots using Heron's method.                           *
 *  Arguments:                                                                *
 *      X (Real):                                                             *
 *          A positive real number.                                           *
 *  OUTPUT:                                                                   *
 *      SqrtX (Real):                                                         *
 *          The square root of X.                                             *
 ******************************************************************************)
Function HeronsMethod(Const X: Real) : Real;

VAR
    Error: Real;
    Iters: Integer;

BEGIN

    (* Heron's method needs a starting value. Pick the input.                 *)
    HeronsMethod := X;

    (*  Iteratively perform Heron's method.                                   *)
    FOR Iters := 0 TO MaximumNumberOfIterations - 1 DO
    BEGIN

        (*  If the error is small we can break out of this loop.              *)
        Error := (X - HeronsMethod * HeronsMethod) / X;

        IF (ABS(Error) < Epsilon) THEN BREAK;

        (*  Otherwise, improve our approximation using Heron's method.        *)
        HeronsMethod := 0.5 * (HeronsMethod + X / HeronsMethod);
    END;
END;

(*  Program for testing our implementation of Heron's method.                 *)
BEGIN

    (*  Compute the square root using Heron's method and print the result.    *)
    SqrtValue := HeronsMethod(Value);
    WriteLn('sqrt(', Value:0:1, ') = ', SqrtValue:0:16);

END.

(*  We can compile this using the Free Pascal Compiler (fpc):                 *
 *      https://www.freepascal.org/                                           *
 *  Once installed, on GNU, Linux, FreeBSD, macOS, etc., this can be run by:  *
 *      fpc herons_method.pas -omain                                          *
 *      ./main                                                                *
 *  This outputs:                                                             *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  The relative error is 1.570092458683775E-16.                              *
 *                                                                            *
 *  On Windows, type:                                                         *
 *      fpc herons_method.pas -omain.exe                                      *
 *      main.exe                                                              *
 *  This produces the same output.                                            *)

IDL

;------------------------------------------------------------------------------;
;                                   LICENSE                                    ;
;------------------------------------------------------------------------------;
;   This file is part of mitx_mathematics_programming_examples.                ;
;                                                                              ;
;   mitx_mathematics_programming_examples is free software: you can            ;
;   redistribute it and/or modify it under the terms of the GNU General Public ;
;   License as published by the Free Software Foundation, either version 3 of  ;
;   the License, or (at your option) any later version.                        ;
;                                                                              ;
;   mitx_mathematics_programming_examples is distributed in the hope that it   ;
;   will be useful but WITHOUT ANY WARRANTY; without even the implied warranty ;
;   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           ;
;   GNU General Public License for more details.                               ;
;                                                                              ;
;   You should have received a copy of the GNU General Public License          ;
;   along with mitx_mathematics_programming_examples.  If not, see             ;
;   <https://www.gnu.org/licenses/>.                                           ;
;------------------------------------------------------------------------------;
;   Purpose:                                                                   ;
;       Calculates roots using the bisection method.                           ;
;------------------------------------------------------------------------------;
;   Author: Ryan Maguire                                                       ;
;   Date:   2025/05/22                                                         ;
;------------------------------------------------------------------------------;
FUNCTION HERON, X

    ; Tells the compiler that integers should be 32 bits, not 16.
    COMPILE_OPT IDL2

    ; Error checking code.
    ON_ERROR, 2

    ; Heron's method is iterative. The convergence is quadratic, meaning the
    ; number of accurate decimals doubles with each iteration. Because of this
    ; we can halt the algorithm after a few steps.
    MAXIMUM_NUMBER_OF_ITERATIONS = 16

    ; Maximum allowed error. This is double precision epsilon.
    EPSILON = 2.220446049250313E-16

    ; Variable used for Heron's approximation. We will iteratively update
    ; this value with better approximations using Heron's method
    APPROXIMATE_ROOT = x

    ; Iteratively perform Heron's method.
    FOR ITERS = 1, MAXIMUM_NUMBER_OF_ITERATIONS DO BEGIN

        ; If the error is small we can break out of this loop.
        ERROR = (X - APPROXIMATE_ROOT * APPROXIMATE_ROOT) / X

        IF (ABS(ERROR) LE EPSILON) THEN BREAK

        ; Otherwise, improve our approximation using Heron's method.
        APPROXIMATE_ROOT = 0.5 * (APPROXIMATE_ROOT + X / APPROXIMATE_ROOT)

    END

    ; If x is positive and not too big, APPROXIMATE_ROOT should have a
    ; very accurate approximation to sqrt(x). Heron's method works for
    ; large inputs as well, but we need to increase the value of
    ; MAXIMUM_NUMBER_OF_ITERATIONS.
    RETURN, APPROXIMATE_ROOT

END

; Program for testing our implementation of Heron's method.
PRO MAIN

    COMPILE_OPT IDL2

    ; The input for the method. We'll compute sqrt(2).
    X = DOUBLE(2.0)

    ; Run the routine, computing sqrt(x), and print the result.
    SQRT_2 = HERON(X)
    PRINT, X, SQRT_2, FORMAT = 'SQRT(%3.1f) = %18.16f'

END

; We can run this by installing the GNU Data Language (GDL), which is
; a free and open source alternative to IDL:
;   https://gnudatalanguage.github.io/
; Once installed, start GDL by typing gdl. Once running, type:
;   GDL> .compile herons_method.pro
;   GDL> main
; This will produce the following output:
;   SQRT(2.0) = 1.4142135623730949
; The relative error is 1.570092458683775E-16.

Python

"""
################################################################################
#                                   LICENSE                                    #
################################################################################
#   This file is part of mitx_mathematics_programming_examples.                #
#                                                                              #
#   mitx_mathematics_programming_examples is free software: you can            #
#   redistribute it and/or modify it under the terms of the GNU General        #
#   Public License as published by the Free Software Foundation, either        #
#   version 3 of the License, or (at your option) any later version.           #
#                                                                              #
#   mitx_mathematics_programming_examples is distributed in the hope that      #
#   it will be useful but WITHOUT ANY WARRANTY; without even the implied       #
#   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           #
#   See the GNU General Public License for more details.                       #
#                                                                              #
#   You should have received a copy of the GNU General Public License          #
#   along with mitx_mathematics_programming_examples. If not, see              #
#   <https://www.gnu.org/licenses/>.                                           #
################################################################################
#   Purpose:                                                                   #
#       Calculates square roots using Heron's method.                          #
################################################################################
#   Author: Ryan Maguire                                                       #
#   Date:   2025/03/08                                                         #
################################################################################
"""

# Pylint doesn't like "x" as a variable name. Disable this warning.
# pylint: disable = invalid-name

# Computes the square root of a positive real number via Heron's method.
def herons_method(x):
    """
        Function:
            herons_method
        Purpose:
            Applies Heron's method to a positive real number, returning
            the square root of it.
        Arguments:
            x (float):
                A positive real number.
        Output:
            sqrt_x (float):
                The square root of x.
    """

    # Heron's method only works for strictly positive real numbers.
    if x <= 0.0:
        raise ValueError("Input must be a positive real number.")

    # Heron's method is iterative and the convergence is quadratic. This
    # means that if a_{n} has N correct decimals, then a_{n+1} will have
    # 2N correct decimals. A standard 64-bit double can fit about 16
    # decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).
    # Because of this we may exit the function after a few iterations.
    maximum_number_of_iterations = 16

    # The maximum allowed error. This is double precision epsilon.
    epsilon = 2.220446049250313E-16

    # Set the initial guess to the input. Provided x is positive, Heron's
    # method will indeed converge.
    approximate_root = x

    # Iteratively loop through and obtain better approximations for sqrt(x).
    for _ in range(maximum_number_of_iterations):

        # If we are within epsilon of the correct value we may break out of
        # this for-loop. Use the absolute value function to check.
        error = (x - approximate_root * approximate_root) / x

        if abs(error) <= epsilon:
            break

        # Apply Heron's method to get a better approximation for the root.
        approximate_root = 0.5 * (approximate_root + x / approximate_root)

    # As long as x is positive and not very large, we should have a very
    # good approximation for sqrt(x). Heron's method will still work for
    # very large x, but we must increase maximum_number_of_iterations.
    return approximate_root

def main():
    """
        Main routine for testing our implementation of Heron's method.
    """
    x = 2.0
    sqrt_x = herons_method(x)
    print(f"sqrt({x}) = {sqrt_x}")

if __name__ == "__main__":
    main()

# We can run this using the standard Python implementation, C-Python:
#   https://www.python.org/downloads/
# Once installed, run:
#   python3 herons_method.py
# Depending on your platform you may need to replace "python3" with "python"
# or "py" or "py3". This will output:
#   sqrt(2.0) = 1.414213562373095
# This has relative error 1.570092458683775E-16.

R

################################################################################
#                                   LICENSE                                    #
################################################################################
#   This file is part of mitx_mathematics_programming_examples.                #
#                                                                              #
#   mitx_mathematics_programming_examples is free software: you can            #
#   redistribute it and/or modify it under the terms of the GNU General        #
#   Public License as published by the Free Software Foundation, either        #
#   version 3 of the License, or (at your option) any later version.           #
#                                                                              #
#   mitx_mathematics_programming_examples is distributed in the hope that      #
#   it will be useful but WITHOUT ANY WARRANTY; without even the implied       #
#   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           #
#   See the GNU General Public License for more details.                       #
#                                                                              #
#   You should have received a copy of the GNU General Public License          #
#   along with mitx_mathematics_programming_examples. If not, see              #
#   <https://www.gnu.org/licenses/>.                                           #
################################################################################
#   Purpose:                                                                   #
#       Calculates square roots using Heron's method.                          #
################################################################################
#   Author: Ryan Maguire                                                       #
#   Date:   2025/05/18                                                         #
################################################################################

# Computes the square root of a positive real number via Heron's method.
herons_method <- function(x) {

    # Heron's method is iterative and the convergence is quadratic. This
    # means that if a_{n} has N correct decimals, then a_{n+1} will have
    # 2N correct decimals. A standard 64-bit double can fit about 16
    # decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).
    # Because of this we may exit the function after a few iterations.
    maximum_number_of_iterations <- 16

    # The maximum allowed error. This is double precision epsilon.
    epsilon <- 2.220446049250313E-16

    # Set the initial guess to the input. Provided x is positive, Heron's
    # method will indeed converge.
    approximate_root <- x

    # Iteratively loop through and obtain better approximations for sqrt(x).
    for (iters in 1:maximum_number_of_iterations) {

        # If we are within epsilon of the correct value we may break out of
        # this for-loop. Use the absolute value function to check.
        error <- (x - approximate_root * approximate_root) / x

        if (abs(error) < epsilon) {
            break
        }

        # Apply Heron's method to get a better approximation for the root.
        approximate_root <- 0.5 * (approximate_root + x / approximate_root)
    }

    # As long as x is positive and not very large, we should have a very
    # good approximation for sqrt(x). Heron's method will still work for
    # very large x, but we must increase maximum_number_of_iterations.
    return(approximate_root)
}

# Test out the function, try computing sqrt(2).
x_val <- 2.0
sqrt_2 <- herons_method(x_val)
output <- sprintf("sqrt(%.1f) = %.16f", x_val, sqrt_2)
message(output)

# We can run this by installing R.
#   https://www.r-project.org/
# Once installed, type:
#   Rscript herons_method.r
# This will output:
#   sqrt(2.0) = 1.4142135623730949
# This has relative error 1.570092458683775E-16.

Rust

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  Computes the square root of a positive real number via Heron's method.    */
fn herons_method(x: f64) -> f64 {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const MAXIMUM_NUMBER_OF_ITERATIONS: u32 = 16;

    /*  The maximum allowed error. This is double precision epsilon.          */
    const EPSILON: f64 = 2.220446049250313E-16;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    let mut approximate_root: f64 = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for _ in 0 .. MAXIMUM_NUMBER_OF_ITERATIONS {

        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        let error: f64 = (x - approximate_root * approximate_root) / x;

        if error.abs() <= EPSILON {
            break;
        }

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximate_root = 0.5 * (approximate_root + x / approximate_root);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase MAXIMUM_NUMBER_OF_ITERATIONS.      */
    return approximate_root;
}
/*  End of herons_method.                                                     */

/*  Main routine used for testing our implementation of Heron's method.       */
fn main()
{
    /*  The input to Heron's method, the value we want to compute the square  *
     *  root of.                                                              */
    let x: f64 = 2.0;

    /*  Calculate the square root and print it to the screen. If we have      *
     *  written things correctly, we should get 1.414..., which is sqrt(2).   */
    let sqrt_x: f64 = herons_method(x);
    println!("sqrt({}) = {}", x, sqrt_x);
}

/*  We can run this by installing the standard rust compiler, rustc:          *
 *      https://www.rust-lang.org/tools/install                               *
 *  On GNU, Linux, FreeBSD, macOS, etc., we can run this by typing:           *
 *      rustc herons_method.rs -o main                                        *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.414213562373095                                         *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows, type:                                                         *
 *      rustc herons_method.rs -o main.exe                                    *
 *      main.exe                                                              *
 *  This will produce the same output.                                        */

Swift

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/03/08                                                        *
 ******************************************************************************/

/*  fabs (floating-point absolute value) found here.                          */
import Foundation

/*  Heron's method is iterative and the convergence is quadratic. This means  *
 *  that if a_{n} has N correct decimals, then a_{n+1} will have 2N correct   *
 *  decimals. A standard 64-bit double can fit about 16 decimals of precision *
 *  (the exact value is 2^-52 ~= 2.22x10^-16). Because of this we may exit    *
 *  the function after a few iterations.                                      */
let maximum_number_of_iterations: UInt32 = 16

/*  The maximum allowed error. This is double precision epsilon.              */
let epsilon: Double = 2.220446049250313E-16

/*  Function for computing square roots using Heron's method.                 */
func heronsMethod(x: Double) -> Double {

    /*  Starting value for Heron's method. The input will suffice.            */
    var approximate_root: Double = x

    /*  Loop through and iteratively perform Heron's method.                  */
    for _ in 0 ..< maximum_number_of_iterations {

        /*  If the error is small enough we can break out of the loop. We     *
         *  want small relative error, so compute this.                       */
        let error: Double = (x - approximate_root * approximate_root) / x

        if fabs(error) <= epsilon {
            break
        }

        /*  Otherwise improve the error by applying Heron's method.           */
        approximate_root = 0.5 * (approximate_root + x / approximate_root)
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method works for large x, but *
     *  we may need to increasethe value of maximum_number_of_iterations.     */
    return approximate_root
}

/*  Test out Heron's method by computing sqrt(2).                             */
let x: Double = 2.0
let sqrt_x: Double = heronsMethod(x: x)
print("sqrt(\(x)) = \(sqrt_x)")

/*  We can run this using the standard swift compiler, swiftc:                *
 *      https://www.swift.org/install/                                        *
 *  After installing, on GNU, Linux, or macOS, type:                          *
 *      swiftc herons_method.swift -o main                                    *
 *      ./main                                                                *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.414213562373095                                         *
 *  This has a relative error of 1.570092458683775E-16.                       *
 *                                                                            *
 *  On Windows, type:                                                         *
 *      swiftc herons_method.swift -o main.exe                                *
 *      main.exe                                                              *
 *  This will produce the same output.                                        */

TypeScript

/******************************************************************************
 *                                  LICENSE                                   *
 ******************************************************************************
 *  This file is part of mitx_mathematics_programming_examples.               *
 *                                                                            *
 *  mitx_mathematics_programming_examples is free software: you can           *
 *  redistribute it and/or modify it under the terms of the GNU General       *
 *  Public License as published by the Free Software Foundation, either       *
 *  version 3 of the License, or (at your option) any later version.          *
 *                                                                            *
 *  mitx_mathematics_programming_examples is distributed in the hope that     *
 *  it will be useful but WITHOUT ANY WARRANTY; without even the implied      *
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 *  See the GNU General Public License for more details.                      *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with mitx_mathematics_programming_examples. If not, see             *
 *  <https://www.gnu.org/licenses/>.                                          *
 ******************************************************************************
 *  Purpose:                                                                  *
 *      Calculates square roots using Heron's method.                         *
 ******************************************************************************
 *  Author: Ryan Maguire                                                      *
 *  Date:   2025/05/18                                                        *
 ******************************************************************************/

/*  Computes the square root of a positive real number via Heron's method.    */
function heronsMethod(x: number): number {

    /*  Heron's method is iterative and the convergence is quadratic. This    *
     *  means that if a_{n} has N correct decimals, then a_{n+1} will have    *
     *  2N correct decimals. A standard 64-bit double can fit about 16        *
     *  decimals of precision (the exact value is 2^-52 ~= 2.22x10^-16).      *
     *  Because of this we may exit the function after a few iterations.      */
    const MAXIMUM_NUMBER_OF_ITERATIONS: number = 16;

    /*  The maximum allowed error. This is double precision epsilon.          */
    const EPSILON: number = 2.220446049250313E-16;

    /*  Variable for keeping track of how many iterations we have performed.  */
    let iters: number;

    /*  Set the initial guess to the input. Provided x is positive, Heron's   *
     *  method will indeed converge.                                          */
    let approximateRoot: number = x;

    /*  Iteratively loop through and obtain better approximations for sqrt(x).*/
    for (iters = 0; iters < MAXIMUM_NUMBER_OF_ITERATIONS; ++iters) {

        /*  If we are within epsilon of the correct value we may break out of *
         *  this for-loop. Use the absolute value function to check.          */
        const error: number = (x - approximateRoot * approximateRoot) / x;

        if (Math.abs(error) <= EPSILON) {
            break;
        }

        /*  Apply Heron's method to get a better approximation for the root.  */
        approximateRoot = 0.5 * (approximateRoot + x / approximateRoot);
    }

    /*  As long as x is positive and not very large, we should have a very    *
     *  good approximation for sqrt(x). Heron's method will still work for    *
     *  very large x, but we must increase MAXIMUM_NUMBER_OF_ITERATIONS.      */
    return approximateRoot;
}
/*  End of heronsMethod.                                                      */

/*  Test out our function, compute sqrt(2) and print it to the screen.        */
const X: number = 2.0;
const SQRT_2: number = heronsMethod(X);
const output: string = "sqrt(2) = " + SQRT_2.toFixed(16);
console.log(output);

/*  We can run this by installing node.js and tsx:                            *
 *      https://nodejs.org/en                                                 *
 *  Using the node package manager (npm), install tsx by typing:              *
 *      npm install -g tsx                                                    *
 *  Run the file by typing:                                                   *
 *      npx tsx herons_method.ts                                              *
 *  This will output the following:                                           *
 *      sqrt(2.0) = 1.4142135623730949                                        *
 *  This has a relative error of 1.570092458683775E-16.                       */