LinuxQuestions.org
LinuxAnswers - the LQ Linux tutorial section.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
LinkBack Search this Thread
Old 02-10-2012, 01:59 PM   #1
smahb001
LQ Newbie
 
Registered: Feb 2012
Posts: 7

Rep: Reputation: Disabled
Question need help for Babylonian SquareRoot using functions


Hi, I did a program in C++ on Babylonion SquareRoot without using any function. The code is given below:
#include <iostream>
using namespace std;
int main()
{
int n, count(10);
double answer_n, guess, r;

cout << "This program will compute the square root of a number using the Babylonian Algorithm:\n";
cout << "Please enter an Integer:\n";
cin >> n;
cout << "Please enter a 'guess' number to divide by:\n";
cin >> guess;

r = n/guess;
guess = (guess + r)/2;

while (count > 0)
{
r = n/guess;
guess = (guess + r)/2;

if (guess <= (guess * 0.01) + guess)
answer_n = guess;
else
r = n/guess;
guess = (guess + r)/2;

count-=1;
}
cout << "The sqaure root of "<< n << " is " << answer_n;
cout << endl;

return 0;

}

This program is fine. I can compile and run it both in Unix and Windows server. But now i want to do it using two function one function should calculate the initial guess. and the other function will calculate SquareRoot iteratively until the difference is below the initialguess or threshold. Then i just call the function from main. Can anybody help me with that? And the program will also print each guess of the input number.
I am just a new learner. If anybody can help me it would be very helpful for me.
 
Old 02-11-2012, 05:42 PM   #2
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,554
Blog Entries: 3

Rep: Reputation: 816Reputation: 816Reputation: 816Reputation: 816Reputation: 816Reputation: 816Reputation: 816
Please use [CODE][/CODE] tags around your code, so that it is easier to read. For one, it retains the indentation.

First question is: How do you calculate the initial guess?

Usually something like this is done using a very simple function, something like
Code:
double initial_guess(const double value)
{
    return value - 1.0;
}
which just returns one less than the value. It is obviously a very bad choice; I just showed that as an example. You might try, for example, halving the original value. I think that would be the simplest good guess. Better guesses exist, but they need a bit more logic, I think.

The const in the parameter declaration tells your compiler that you will not be changing the value of value inside your function, so it can be heavily optimized (cached) during calculations. It leads to better code. In any case, function parameters are passed by value; without the const, you can change value, but those changes are visible only within the function, they're not propagated to the caller.

The second function is a classical case of iteration. The important parts for such a function for me would be
Code:
double babylonian_square_root(const double value, const double guess, const double maxerror)
{
    const double maxsquared = maxerror * maxerror;
    double       answer = guess;
    double       error;

    if (value <= 0.0)
        return 0.0;

    do {

        /*
         * Calculate new answer here
        */

        error = value - answer * answer;

    } while (error * error > maxsquared);

    return answer;
}
Note that this has no iteration limit: if your answer does not eventually arrive at a good enough solution, the loop will run forever.

There is a very practical trick here, too: I am using the square of the error to determine when the result is good enough. Main reason is that square is always positive. (Otherwise you'd have to take the absolute value of the error for comparison.) Another reason is the limited precision of floating-point numbers: squaring helps avoid precision-related issues near zero, because values close to zero will be treated as real zeros.

Instead of having the guess as a parameter, you could also omit it from the function parameter list, then use answer = initial_guess(value); before the do loop. In that case this latter function would automatically call the first function to obtain the initial guess.
 
Old 02-12-2012, 10:39 AM   #3
smahb001
LQ Newbie
 
Registered: Feb 2012
Posts: 7

Original Poster
Rep: Reputation: Disabled
Thanks a lot Nominal Animal. It was really very helpful.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
OSE system call functions to Linux Sytem Call functions required roshantraj30 Linux - General 0 06-09-2009 10:44 AM
LXer: OpenOffice.org Calc functions, part 1: Understanding functions LXer Syndicated Linux News 0 03-31-2007 12:01 PM
Slackpkg: missing something in /usr/libexec/slackpkg/functions.d/dialog-functions.sh michelino Slackware 4 03-20-2007 12:22 PM
squareroot program problem, i cant compile it ARGH! inverted.gravity Programming 5 02-15-2006 01:38 AM
pointers to functions/member functions champ Programming 2 03-28-2003 06:22 PM


All times are GMT -5. The time now is 02:34 PM.

Main Menu
 
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration