Calculating a SquareRoot

Here an “Indy” way to calculate an (approximate) squareRoot



public class CalcSquareRoot {


	public static void main(String[] args) 
	
	{
	
		//number to calc root of
		double base=544.5;
		
		double adder=1;
		double sum=0;
		double counter=0;
		
		double comp = base*1000000;
		
		while(sum<comp) {counter++;sum+=adder;adder+=2;}
		
		System.out.println("for "+ base + "\n root is about: "+(counter/1000) + "\n actual root is: " + Math.sqrt(base));
		
	}

}


A similar method was used in the very first pocket calculators.

Dam that is cool! :smiley:

Here just using ints, adding, bitshifting and multiplication

(more close to primitive processors)



public class CalcSquareRoot {


	public static void main(String[] args) 
	
	{
	
		//number to calc root of
		int base=544544;
		
		int adder=1;
		int sum=0;
		int counter=0;
		
		int comp = base<<8;
		
		while(sum<comp) {counter++;sum+=adder;adder+=2;}
		
		System.out.println("for "+ base + "\n root is about: "+(counter>>4) + "\n actual root is: " + Math.sqrt(base) + "\n processing steps taken:" + counter);
		
	}

}

Neat! Was disappointed it couldn’t handle the decimals in the square root of 2.0 though.

Reminds me of SICP lectures online, from MIT (Abelson and Sussman, 1986). Early on there is a square root program using LISP and recursion.

Using Clojure, I wrote the following based on their LISP listing.


(defn sqrt [v]
  (defn avg [v1 v2] ( / ( + v1 v2 ) 2 ) )
  (defn sq [v] ( * v v ) )
  (defn abs [v] ( if ( < v 0 ) ( * -1 v) v ) )
  (defn good-enough? [v1 v2] ( < ( abs ( - v1 v2) ) 0.00001 ) )
  (defn improve-guess [v1 v2] ( avg v1 ( / v2 v1 ) ) )
  (defn try-guess [v1 v2] 
    ( if 
      (good-enough? (sq v1) v2) 
      v1 
      (try-guess (improve-guess v1 v2) v2))
    ) 
  (try-guess 1 v)
)
(sqrt 2.0)

I’m five videos in so far. It’s a very interesting set of lectures. I suppose I could have written their examples in Java, but it seems like a good opportunity to get acquainted with a LISP-based language, and Clojure purports to have a lot to offer in terms of gaining functional programming chops.

Note: you can’t the beat hardware these days.

Christ, all those lines and CPU hugging.


	public final static float inverseSqrt(float x) {
		final float xhalves = 0.5f * x;
		x = (float)(Double.longBitsToDouble(0x5FE6EB50C7B537AAl - (Double.doubleToRawLongBits(x) >> 1)));
		return x * (1.5f - xhalves * x * x);
	}

	public final static float sqrt(final float x) {
		return x * inverseSqrt(x);
	}


Interesting read.

This is like Nerd heaven :wink: