Monday, May 2, 2011

Write a function that computes log2() using sqrt().

Well Its Very Interesting &n Tough Question Unless You Think ..Most of Us Stuck Whats The Use of Sqrt(0 to calculate log2() ..isn't it..?? i also stuck 1st but after doing some stuff with maths i was able to come up with this Algorithm so It Can be Done Using Simple Maths

As we Know

sqrt(x) = x^1/2

ln2(x) = ln(x) / ln(2)

ln2(sqrt(x)) = ln( x^(1/2) ) / ln(2)
= ((1/2) ln(x)) / ln(2)
= (1/2) * ln2(x)

So ln2(x) = 2 * ln2(sqrt(x))




class log_2
{

static double ln2;
static double epsilon = 0.0000001;

public static void main(String[] args)
{

ln2 = Math.log(2);

System.out.println("log2(10) = " + log2(10));
System.out.println("log2(10) = " + Math.log(10)/ln2);

}

public static double log2(double x)
{
if( x - 1 < epsilon ){

return (x-1)/ln2;
}
else{

return log2( Math.sqrt(x) ) * 2;
}
printf( " %d ", x/2);
}
}


Correctness Depends on epsilon value e.g no of places after decimal
Expected Output log2(10) = 3.3219282055116603
Actual Output log2(10) = 3.3219280948873626



Also You Know Taylor Series Extension of Log(1+x)= x - x^2/2 + x^3/3 + ... + ((-1)^(i+1).x^i)/i + o(x^(i+1))

More info http://en.wikipedia.org/wiki/Binary_logarithm

No comments :