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?

12
Contributors
14
Replies
24
Views
10 Years
Discussion Span
Last Post by mikrosfoititis
Featured Replies
• 1

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 …

• 1
Salem 5,138   10 Years Ago

[url]http://en.wikipedia.org/wiki/Methods_of_computing_square_roots[/url] 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".

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.

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.

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...

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.

Votes + Comments
great explination

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();
}

Edited by dnshackme: n/a

#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);

}

Edited by caut_baia: n/a

...you may use bisection method..

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

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).

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

Of course you could always write your own ln function.

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!!!!

>> 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.

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

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.