C# implementation of Babylonian Method – method to calculate square root of positive numbers.

IN
3
0.0000000001
OUT
sqrt(3) = 0.3
sqrt(3) = 5.15
sqrt(3) = 2.86626213592233
sqrt(3) = 1.9564607317769
sqrt(3) = 1.74492093914502
sqrt(3) = 1.73209827111954
sqrt(3) = 1.73205080821918
using System;

// © 2018 TheFlyingKeyboard and released under MIT License 
// theflyingkeyboard.net
namespace BabylonianMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            double number = 0.0;
            double precision = 0.0;

            Console.WriteLine("Enter number to square root");
            number = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Enter precision");
            precision = Convert.ToDouble(Console.ReadLine());

            if (number < 0)
            {
                Console.WriteLine("Number must be >= 0");
                return;
            }

            if (number == 0)
            {
                Console.WriteLine("sqrt(0) = 0");
                return;
            }

            double x = number / 10;
            double y = number / x;

            do
            {
                Console.WriteLine("sqrt(" + number + ") = " + x);
                x = (x + y) / 2;
                y = number / x;
            } while (x - y > precision);

            Console.ReadKey();
        }
    }
}

 



C# Babylonian Method – SQRT()
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close