954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is it possible to create a square root program without math.h

I have created a program without using sqrt and the pwr function but instead have used logs and exponent.

The professor said that math.h is not allowed. I am aware that this library is important for computation, but how do I compute the math without using the math.h?

Would I need to create my library if so how?

tformed
Junior Poster in Training
58 posts since May 2007
Reputation Points: 21
Solved Threads: 1
 

That depends what the program is. I doubt that he's asking you to rewrite the sqrt, log and pow functions from math.h (Unless your course is a mathematics one).

if you post a description of your problem, and the code from your current solution, there might be another way to do it.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

Can't you use loops and division and multiplication to get the square root ? For example, the square root of 16 can be found by trial-and-error multiplying 1*1, then 2*2, then 3*3, then 4*4 until you get a number that is close to the original number.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Keep dividing by "test numbers" until the modulus and the test number are equal. Of coarse things will get a bit stickier when the square root is a non-integer...

JRM
Practically a Master Poster
621 posts since Nov 2006
Reputation Points: 130
Solved Threads: 75
 

More specifically, one way is binary search. Given a range [low, high] in which your square root lies, you can test if the square of (low + high) / 2 is greater than the value you're square rooting or not. If it's greater, then your new range is [low, (low + high)/2], if less, then your new range is [(low + high)/2, high]. Keep narrowing this range in half until the value (low + high)/2 is either <= low or >= high (which it will be, eventually, because you're using doubles.)

You need to pick appropriate starting values of low and high, of course -- one choice is 1 and the number you're taking the square root of.

This algorithm is rather slow, requiring about 52 or 64 iterations for reasonable numbers (if you're using the double datatype), but if if the number you're square-rooting is very, very close to zero, it will have to run thousands of iterations before it terminates (because instead of running into the limits of a double's precision, you'll be descending down to lower and lower exponents). Maybe you'd then want to make 0 a special case, tested for at the beginning.

A faster algorithm to find the square root of x is to compute f(f(...(f(f(f(f(1))))...)), where f(y) = (x/y + y)*0.5, and where f is iterated sufficiently many times.

Rashakil Fol
Super Senior Demiposter
Team Colleague
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
 

http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
The math.h implementation of sqrt() could well use one (or more) of the methods outlined in the link.

You too could implement the algorithms, and not rely on "math.h".

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

THIS MIGHT HELP YOU

/*Square root of a number using Babylonian method of average of guesses */
main()
{
int i,x;
float s;
printf("Enter a number : ");
scanf("%d",&x);
s=((x/2)+x/(x/2))/2;/*first guess*/
for(i=1;i<=4;i++)/*average of guesses*/
{
s=(s+x/s)/2;
}
printf("Sqrt %d = %f",x,s);/*~approx*/
getch();
}
dnshackme
Newbie Poster
1 post since Aug 2011
Reputation Points: 10
Solved Threads: 0
 
#include <iostream>

#include <deque>

#include <string>

#include <limits>

#include <sstream>

#include <iomanip>

#include <cmath>



/* Obtaining square root using the decimimal method */



class square_root  {

   double result,tmp,rmndr;                                    																						

	long input;

	double decim;              //Will contain the number of trailing decimimals.

	std::deque<double> tokens; //Will contain the tokenized 'input' value.

	square_root ();           



	/* Aproximates the biggest number 'n' given as input 'a' and 'x' such that ( y=(a*20)+n | x - (y*n) < y )  */

	double aprox (double a,double x)  {    

		double ret=1;

		a*=20;

		while ((a+ret)*ret <= x)  {

			ret++;

		 }

		ret--;

		return ret;

	 }



        void sqt (double num,bool point=0)  {        // 3  45  34. 00    | 185.8

		rmndr*=100;                          // 3-               |________________________________________

		rmndr+=num;                          // 1=               | 1*1=1 < 3                      => 1

		tmp=aprox (result,rmndr);            //   245-           | (((1*2)*10)+8)*8=224 < 245     => 8

		rmndr-=((result*20)+tmp)*tmp;        //   224            | 

		result*=10;                          //      2134-       | (((18*2)*10)+5)*5=1825 < 2134  => 5

		result+=tmp;                         //      1825        |

		if (point==1)  {                     //          33900   | (((185*2)*10)+8)*8=29664 < 33900 => 0.8

		        decim*=10;

		 }			

	 }

	

	/* Tokenizes a number by grouping it's digits in pairs of two from back to front

	 * and stores them in the vector 'tokens'.

	 *		ex: input=3453545;  

	 * Now the vector 'tokens' will contain four objects (45,35,45,3) 

	 */



	void tokenize (long inp)  {

		const long step=100;

		for (long x=step,y=1;x <= inp*step;x*=step,y*=step)  {

			double tok=((inp%x - inp%y) / y);

			tokens.push_front (tok);

		 }

	 }



public:

	explicit square_root (long input_) : input(input_), result(0), rmndr(0), tmp(0), decim(1)  {

		if (input <= std::numeric_limits<long>().max())  {

			tokenize (input);

			for (std::deque<double>::iterator i=tokens.begin();i!=tokens.end();++i)  {				

				sqt (*i);

			 }			

			for (int x=0;x<square_root::precision;x++) sqt(0,1); //calling sqt with 'point' set starts counting trailing decimals

			/* Dividing to the apropriate value */

			result/=decim;

		 }		

	 }

        ~square_root () {}



	static const int precision=25;

	operator double () const  {

		return result;

	 }

 };



int main (int argc,char* argv[])  {	

	long n;

	std::stringstream (argv[1]) >> n;

	std::cout << "\n\n\n" << std::fixed << std::setprecision(square_root::precision) << square_root (n) << "\n\n\n\n";

	std::cout << std::sqrt (n);

 }
caut_baia
Posting Whiz
387 posts since Apr 2010
Reputation Points: 25
Solved Threads: 49
 

...you may use bisection method..

and of course, for loop or do while method in c++.. try it! :)

navtz03
Newbie Poster
1 post since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Why not use e^((ln(x))/2) ? That's the formula they use to find square roots (x is the number to be calculated and e is the know constant).

mikrosfoititis
Junior Poster in Training
74 posts since Nov 2011
Reputation Points: 18
Solved Threads: 11
 

and where do you get the ln() function? Frommath.h? Which can't be used?

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Of course you could always write your own ln function.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Dude relax just see documentation of math.h or cmath copy and paste the fucntions for sqrt and done.....make ur own header file.........

haaa.......the easiest approach....

and read the coding again and again and analyze the comments provided to get complete knowledge of ur copy paste header file!!!!

ishaan3731
Newbie Poster
14 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
 

>> just see documentation of math.h or cmath copy and paste the fucntions for sqrt and done.

The code for the functions isn't in math.h, only function prototypes. So copying them is little or no value.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
and where do you get the ln() function? Frommath.h? Which can't be used?

Uhm... Yes, you have a point there :P

mikrosfoititis
Junior Poster in Training
74 posts since Nov 2011
Reputation Points: 18
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You