| | |
Square root program without sqrt or pwr
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Aug 2009
Posts: 55
Reputation:
Solved Threads: 0
>Unfortunately, this type of religious fanatic non-logic is also quite typical of Microsoft haters.
Dear Narue,
Your insinuation might be unfair.
Contrary to your misconception, I believe I am a reasonable man.
I can accept that "it is better to let 10 guilty persons go free, than to wrongfully accused a single innocent person." Can you?
My personal conviction on a Company or an individual is, to my best knowledge, not based some religious, fanatical and illogical prejudice, but on solid, indisputable and unequivocal evidence.
There got to be some justification in my conviction basing on the common knowledge that there was a historic DOJ anti-trust lawsuit, billion dollars lawsuits (1.5b) in America, hundred of million lawsuits (613m) in Europe and tens of million (32m) lawsuits in Asia -- across 3 continents -- and eventual unfavorable findings against a particular Company. Besides, I have my personal grievances as well, but, I would refrain from dwelling more on this because it is off-topic. I reply basing on an individual's inalienable right to self-defence.
Shall we leave it as it is?
I would refrain from making judgment on you. But, I would make a guess. You were probably an excellent debater in your schooldays. You could get out from tight corners. And you can write very well.
>Borland, huh?
As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum. Most of the time, I am using CODE::BLOCK and Dev-C++ now, being introduced indirectly and directly to it, respectively in this forum. But I sometimes use Borland for references because of its useful references and examples. I guess, if a program could run under Borland, most other modern compilers may work with some minor modifications, and I know how to do it, as I have pointed out in some earlier postings, for the benefit of new C++ programmers like me.
I use the compiler which seem to support most codes I see in this forum. I am not biased. I adapt myself to what is needed to learn C++. For the purpose of coding C++ program, I have dropped Borland in favor of CODE::BLOCK and Dev-C++, because I get the impression that very many posters seem to be using the latter. However, if the majority of posters eventually shift towards MS Visual C++, I might have to follow suit despite my personal convictions about freedom from the stranglehold of some domineering behemoth.
As Don Corleon said, it is strictly business, nothing personal.
Coming back to the matter raised in this thread, I am really surprised at the number of recent postings which revealed that there are many intelligent and good C++ proqrammers in this forum, whose interest in solving this squareroot problem might have been inadvertently rekindled. Some solutions appeared to be incredibly simple, and yet might work. I am indeed interested to test them with my limited knowledge in C++.
Dear Narue,
Your insinuation might be unfair.
Contrary to your misconception, I believe I am a reasonable man.
I can accept that "it is better to let 10 guilty persons go free, than to wrongfully accused a single innocent person." Can you?
My personal conviction on a Company or an individual is, to my best knowledge, not based some religious, fanatical and illogical prejudice, but on solid, indisputable and unequivocal evidence.
There got to be some justification in my conviction basing on the common knowledge that there was a historic DOJ anti-trust lawsuit, billion dollars lawsuits (1.5b) in America, hundred of million lawsuits (613m) in Europe and tens of million (32m) lawsuits in Asia -- across 3 continents -- and eventual unfavorable findings against a particular Company. Besides, I have my personal grievances as well, but, I would refrain from dwelling more on this because it is off-topic. I reply basing on an individual's inalienable right to self-defence.
Shall we leave it as it is?
I would refrain from making judgment on you. But, I would make a guess. You were probably an excellent debater in your schooldays. You could get out from tight corners. And you can write very well.
>Borland, huh?
As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum. Most of the time, I am using CODE::BLOCK and Dev-C++ now, being introduced indirectly and directly to it, respectively in this forum. But I sometimes use Borland for references because of its useful references and examples. I guess, if a program could run under Borland, most other modern compilers may work with some minor modifications, and I know how to do it, as I have pointed out in some earlier postings, for the benefit of new C++ programmers like me.
I use the compiler which seem to support most codes I see in this forum. I am not biased. I adapt myself to what is needed to learn C++. For the purpose of coding C++ program, I have dropped Borland in favor of CODE::BLOCK and Dev-C++, because I get the impression that very many posters seem to be using the latter. However, if the majority of posters eventually shift towards MS Visual C++, I might have to follow suit despite my personal convictions about freedom from the stranglehold of some domineering behemoth.
As Don Corleon said, it is strictly business, nothing personal.
Coming back to the matter raised in this thread, I am really surprised at the number of recent postings which revealed that there are many intelligent and good C++ proqrammers in this forum, whose interest in solving this squareroot problem might have been inadvertently rekindled. Some solutions appeared to be incredibly simple, and yet might work. I am indeed interested to test them with my limited knowledge in C++.
•
•
Join Date: Aug 2009
Posts: 55
Reputation:
Solved Threads: 0
Round 2 - Final round?
--------------------------
To date, 8 working algorithms for computing square-roots are as follows:
opt.1 (tformed) exp() algorithm
opt.2 (Sturm) looping algorithm
opt.3 (Salem) suggested common log algorithm
opt.4 (firstPerson) natural log algorithm
opt.5 (firstPerson) Taylor's series
opt.6 (firstPerson) Brute force
opt.7 (invisal) Inverse Square Root
opt.8 (Foamgum) Spirit MySQRT
NathanOliver's ambitious nth root of a number algorithm has a bug in line 17, which gave rise to infinite loops. firstPerson's Brute force algorithm is original and simplest and the speed may probably be improved if the first computed estimate of the square root of a number entered can be used in the for loop, instead of starting from 0. Precision may have to be sacrificed to increase speed of computation.
The Sqrt program below is used for comparison of performance of the algorithms. Numbers up to 30, 40, 50 and 60 digits data are entered, and the answers given by various algorithms are used for ranking. e.g. a 30-digit number would look like this, 123456789012345678901234567890.
Slow algorithms are skipped, and are considered out of the race.
This time around, the top two entries can match C++'s square root function to the best of my knowledge. However, I may be wrong. Basing on the results, I would rank -- without any bias -- the algorithms in terms of originality and performance as follows:
Foamgum's Spirit MySQRT algorithm (opt. 8) - First place.
firstPerson's Taylor series algorithm (opt.5) - Second place.
invisal's inverse Square Root algorithm (opt.7) - third place.
Foamgum's algorithm is original and answers for numbers up to 60 digits number are correct.
firstPerson's Taylor's series algorithm's answers for numbers up to 60 digits are correct.
invisal's Inverse Square root algorithm uses a magic hex constant. Its answers for numbers up to 30 digits are correct, and for numbers from 40 digits onwards are not correct. Perhaps invisal can debug the codes, and let us have the debugged version. But, if it can only handle float and not double numeric variable, can greater accuracy be achieved? I am curious to know the answer.
Other algorithms were either too slow, were disqualified or could not work (got bug/s).
Run the program below to confirm the above results yourself.
Please feel free to modify the codes to improve them, and kindly post modified parts for me to update my codes. Thanks.
--------------------------
To date, 8 working algorithms for computing square-roots are as follows:
opt.1 (tformed) exp() algorithm
opt.2 (Sturm) looping algorithm
opt.3 (Salem) suggested common log algorithm
opt.4 (firstPerson) natural log algorithm
opt.5 (firstPerson) Taylor's series
opt.6 (firstPerson) Brute force
opt.7 (invisal) Inverse Square Root
opt.8 (Foamgum) Spirit MySQRT
NathanOliver's ambitious nth root of a number algorithm has a bug in line 17, which gave rise to infinite loops. firstPerson's Brute force algorithm is original and simplest and the speed may probably be improved if the first computed estimate of the square root of a number entered can be used in the for loop, instead of starting from 0. Precision may have to be sacrificed to increase speed of computation.
The Sqrt program below is used for comparison of performance of the algorithms. Numbers up to 30, 40, 50 and 60 digits data are entered, and the answers given by various algorithms are used for ranking. e.g. a 30-digit number would look like this, 123456789012345678901234567890.
Slow algorithms are skipped, and are considered out of the race.
This time around, the top two entries can match C++'s square root function to the best of my knowledge. However, I may be wrong. Basing on the results, I would rank -- without any bias -- the algorithms in terms of originality and performance as follows:
Foamgum's Spirit MySQRT algorithm (opt. 8) - First place.
firstPerson's Taylor series algorithm (opt.5) - Second place.
invisal's inverse Square Root algorithm (opt.7) - third place.
Foamgum's algorithm is original and answers for numbers up to 60 digits number are correct.
firstPerson's Taylor's series algorithm's answers for numbers up to 60 digits are correct.
invisal's Inverse Square root algorithm uses a magic hex constant. Its answers for numbers up to 30 digits are correct, and for numbers from 40 digits onwards are not correct. Perhaps invisal can debug the codes, and let us have the debugged version. But, if it can only handle float and not double numeric variable, can greater accuracy be achieved? I am curious to know the answer.
Other algorithms were either too slow, were disqualified or could not work (got bug/s).
Run the program below to confirm the above results yourself.
Please feel free to modify the codes to improve them, and kindly post modified parts for me to update my codes. Thanks.
C++ Syntax (Toggle Plain Text)
// sqrt InputCtrl & sqrt YBM 22 Sep 2009 #include <windows.h> // WinApi header #include <iostream> #include <string> #include <conio.h> #include <math.h> #include <stdlib.h> #include <iomanip> #include <stdio.h> #define maxloop 5 using namespace std; string spaz(int&,int,string); string datainp(string,int); int escx=0; int curs=0; int extended=0; string concate = ""; double weight; double x; char *endptr; string sweight; void gotoxy( short x, short y ) { HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); COORD position = { x, y }; SetConsoleCursorPosition( hStdout, position ); } double sturmsqrt(double num) { double mod=1; double c=0; for(int d=0; d<10000000; c+=mod, d++) if(c*c>num) { c-=mod; mod/=10; } return c; } float invsqrt(float zx) { float xhalf = 0.5f*zx; int i = *(int*)&zx; i = 0x5f3759df - (i>>1); zx = *(float*)&i; for(int k=0; k<5; k++) zx*=(1.5f - xhalf*zx*zx); return 1.0f/zx; } double taylor(double zx) { // Taylor series double k = 1, lim2 = 168; double term; double x=log(zx)/2; double y; double sum = 1; int i=1; y=1; sum = 1; do { k *= i++; y *= x; term = 1.0*y/k; sum += term; } while (i <= lim2); return sum; } float SquareRootOf(double num) { // firstPerson's BRUTE FORCE SQRT Check for perfect square root int i = 0; for(i = 0;i < 10000 ; i++) { if(i * i > num) break; else if(i * i == num) return double(i); } i -= 2; double j = i; float precision = 0.001f; while(j * j < num - precision ) j+=precision; return j; } double MySQRT(double number, int *iterations) { // Foamgum's Spirit MySQRT double b, c, e(1e-12), f; if(number < 0) return -1; while(e > number) // For very small values the criterion for stopping needs to be smaller. e /= 10; b = (1.0 + number)/2; // First estimate of square root of number. c = (b - number/b)/2; // Correction to give a better estimate. while(c > e && (*iterations) < 1000) { f = b; // For very small and very large values we will see b -= c; // if the correction has any effect. if(f == b) // Applying the correction made no difference to our answer. return b; c = (b - number/b)/2; // A revised correction. ++(*iterations); // A counter to measure the effectiveness of our algorithm. } return b; } int xcz=0; int decf=0; int ctr =0; int cc=0; int brk=0; int len=0; std::string xcon; char inpg,xconcate; int getch(void); int getche(void); int xc[maxloop]={5,5,8,5,5}; // xy coordinate starting from zero int yc[maxloop]={11,11,7,17,19}; int lgth[maxloop]; int condi=3; char efld[maxloop][25] = {" "," ","Number : "," "," "}; double e=2.7182818283; int main() { double num; num=0; double heyyou,whome; brk=0; system ("color 0a"); do { system ("CLS"); cout << "\n\tEsc:Exit FINDING THE SQUAREROOT OF A NUMBER"; cout << "\n\tOnly numbers and 1 dec. allowed, (codes may not be bug-free) "; cout << "\n\tNumbers upto 1 trillion seem okay for opt.2 "; cout << "\n\tNumbers above 10 trillion seem okay for opt.1, 3, 4, 5"; cout << "\n\tUse at your own risk. "; sweight=datainp(efld[condi],condi); len=sweight.length(); concate=""; if (brk==1) {break;} num=weight; if (num >0) { whome=num; heyyou= exp((1.0/2.0)*log(whome)); // double exp(double arg); is the same as e (2.7182818283) raised to the argth power, identical with opt.4. cout << "\n\t0. (C++ sqrt() Ans.: "<< sqrt(num); cout << "\n\t1. (tformed)'s exp()sqrt algorithm. Ans.: "<< heyyou; cout << "\n\t2. (Sturm)'s Sturmsqrt algorithm. Ans.: "<< sturmsqrt(num); x = pow(10,log10(num)/2); cout << "\n\t3. (Salem) Common log - pow(10,log10(num)/2). Ans.: " << x; x = pow(e,log(num)/2); cout << "\n\t4. (firstPerson) Natural log - pow(e,log(num)/2). Ans.: " << x; x = taylor(num); cout << "\n\t5. (firstPerson) Taylor Series Ans.: " << x; if (num <= 1000000000) { float(x) = SquareRootOf(num); cout << "\n\t6. (firstPerson) Brute force Ans.: " << x; } else { cout << "\n\t6. (firstPerson) Brute force skip "; } float fnum; fnum=float(num); x = invsqrt(fnum); cout << "\n\t7. (invisal) Inv.SquareRoot, hex const.0x5f3759df.Ans.: " << x; double a, b; // Foamgum int count(0); a = num; b = MySQRT(a, &count); cout << "\n\t8. (Foamgum) Spirit MySQRT Ans.: " << b; } else {cout <<"\x7";} cout << "\n\n\t<Press Any to cont.> "; getch(); } while ( brk==0); cout << "\n\n\tBye. Thanks for trying out Homemade SQRT\n"; cout << "\n\tand Homemade InputCtrl (Feedback, pls.still under construction>\n\n"; } // Data Entry subroutine by YBM string datainp(string efield,int condi) { int c; redo: extended=0; curs=0; decf=0; //std::string concate = ""; gotoxy(xc[condi-1],yc[condi-1]); cout << efld[condi-1]; // gotoxy(xc[condi-1]+lgth[condi-1],yc[condi-1]); do { c = getch(); if (c==27) { brk=1;break; } char inp=c; // assign char from ASCII code Backspace's ASCII code is 8 inpg==inp; extended==0; // cout << "ASCII code of " << inpg << "=" << c; if (c == 0x00 || c == 0XE0 || c==224 || c==0) { extended = getch(); // cout << " EXTENDED: " << extended << "XXX"; cout << "\x7"; if (extended) { c= extended; inp=(char)NULL; inpg==inp; } } if (condi==3) { // Only Numbers and decimal ASCII 46 allowed if (extended==0 && (((decf <=1) && ((c >=48 && c <=57) || c==46)) || ((c >=48 && c <=57) || c==46) && (decf==0) && c !=8)) { if ((decf==0) || (decf >=1 && c != 46)) { concate += inp; // string concatenation.. The character isn't extended cout << inp; } if (c==46 && decf==0) { ++decf;} } else { concate=spaz(condi,c,concate);if (curs==1) {}} } } while (c != 13); // ascii 13 is <enter> or <carriage return> if (c !=27) { int len = concate.length(); // cout << "\n String length =" << len << " chars" << endl; if (condi==3) { // convert string to numeric variable char xxc[len]; // intialise array concate.copy(xxc,len); // fills in array with characters from the string // xxc=concate.c_str(); weight = strtod(xxc,&endptr); // weight declared as global double } } return concate; } // datainput End // SUBROUTINE TO MOVE CURSOR POSITION Up/Dn/LF/RT/PgUp/PgDn by YBM string spaz(int& condi,int xcz,string xconcate) { if (extended >0) { cout << "\x7"; if (xconcate.length()==0) { cout << "\x08"; cout << " ";} // gotoxy(xc[condi]+lgth[condi],yc[condi]); if (xcz==72 || xcz==73 || xcz==75 || xcz == 77 || xcz == 80 || xcz==81) { cout << "\x7"; if (xcz==72 || xcz==77 || xcz==73) { curs=1; if (condi >1) { } } if (xcz==80 || xcz==75 || xcz==81) { curs=1; if (condi < maxloop) { } } extended=0; } extended=0; } else { if (xcz !=8) { // not backspace } else { len = xconcate.length(); if (len >0) { if (condi==3) { if (decf >=1 && xconcate.substr(len-1,1)=="."){ --decf; } } cout << "\x08"; cout << " "; cout << "\x08"; xconcate=xconcate.substr(0,len-1); } else { cout << ""; decf=0; } } } return xconcate; } // spaz End
>Your insinuation might be unfair.
Says the dude who uses the vendor's history of business practices as justification for attacking a very good tool. Based on facts or not, your reasoning is flawed. Consider the following statement, which is false in exactly the same way:
The flaw is easier to see now, I hope. Clearly being an ******* doesn't have any bearing on one's ability to write excellent software. Microsoft's compiler is one of the better ones out there both in terms of performance and standard compliance.
>>Borland, huh?
>As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum.
Actually, I was subtly informing you that the code was written using VCL, a GUI API supplied with Borland C++ Builder. Your initial assumption that the code was written with Visual Studio was off by an entire corporation. That's what I found so amusing about your rant. I'm not sure what you mean by unpopularity on this forum though. I haven't noticed any particular bias against Borland, and personally I'm rather partial to their C++ compiler, it's very nice.
Says the dude who uses the vendor's history of business practices as justification for attacking a very good tool. Based on facts or not, your reasoning is flawed. Consider the following statement, which is false in exactly the same way:
•
•
•
•
"That programmer is an *******, so he must write horrible software."
>>Borland, huh?
>As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum.
Actually, I was subtly informing you that the code was written using VCL, a GUI API supplied with Borland C++ Builder. Your initial assumption that the code was written with Visual Studio was off by an entire corporation. That's what I found so amusing about your rant. I'm not sure what you mean by unpopularity on this forum though. I haven't noticed any particular bias against Borland, and personally I'm rather partial to their C++ compiler, it's very nice.
I'm here to prove you wrong.
I like that comparison, younghc, even though your code is not easy
to follow. Its pretty neat.
to follow. Its pretty neat.
I give up!
1) What word becomes shorter if you add a letter to it? [ Solved by : niek_e ]
2) What does this sequence equal to : (.5u - .5a)(.5u-.5b)(.5u-.5c) ...
3) What is the 123456789 prime numer?•
•
Join Date: Aug 2009
Posts: 55
Reputation:
Solved Threads: 0
Dear Narue,
>....attacking a very good tool....
I do not recall attacking any Corporation's compiler. Where is your evidence, else was it a hallucination?
My conviction in favor of freedom of choice of compilers is entrenched in my belief that there should be healthy competition in mass market consumer software, like in this thread for the benefit of consumers. The problem with monopoly is that quality could be compromised if consumers have no choice. The monopoly vendor who produces an inferior product says, "Take it or leave it". and if you leave it, you have nothing. You wouldn't be happy if something inferior is rammed down your throat, right? That was proven by the overwhelmingly widespread use of Windows OS in PCs, exceeding 90% despite the superiority of Apple OS over Windows, which was at least 7 years behind when Windows95 was first launched. Millions of PC users had to live with an relatively inferior product vis-a-vis Apple. However, the perpetuality clause in a settlement agreement in a Apple's lawsuit against Microsoft lawsuit -- which Apple won --enabled Windows to copy Apple perpetually.
>>Borland, huh?
>As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum.
Thanks for pointing out my wrong assumption. I am a novice learning from all of you.
I got the impression from this forum that Turbo C++, a Borland product was 20 years too late, from postings by Salem and Ancient Dragon, two respectable posters in this forum. Do you mean to say there are improved C++ compiler by Borland which would reject Void main(void)? As I am new, along with many others in this forum, please enlighten us. Please provide the link to the improved Borland, and also to VCL GUI API if it is possible. Thanks.
Regards,
>....attacking a very good tool....
I do not recall attacking any Corporation's compiler. Where is your evidence, else was it a hallucination?
My conviction in favor of freedom of choice of compilers is entrenched in my belief that there should be healthy competition in mass market consumer software, like in this thread for the benefit of consumers. The problem with monopoly is that quality could be compromised if consumers have no choice. The monopoly vendor who produces an inferior product says, "Take it or leave it". and if you leave it, you have nothing. You wouldn't be happy if something inferior is rammed down your throat, right? That was proven by the overwhelmingly widespread use of Windows OS in PCs, exceeding 90% despite the superiority of Apple OS over Windows, which was at least 7 years behind when Windows95 was first launched. Millions of PC users had to live with an relatively inferior product vis-a-vis Apple. However, the perpetuality clause in a settlement agreement in a Apple's lawsuit against Microsoft lawsuit -- which Apple won --enabled Windows to copy Apple perpetually.
>>Borland, huh?
>As I was new to C++, I started with Borland C++, knowing nothing about its unpopularity in this forum.
Thanks for pointing out my wrong assumption. I am a novice learning from all of you.
I got the impression from this forum that Turbo C++, a Borland product was 20 years too late, from postings by Salem and Ancient Dragon, two respectable posters in this forum. Do you mean to say there are improved C++ compiler by Borland which would reject Void main(void)? As I am new, along with many others in this forum, please enlighten us. Please provide the link to the improved Borland, and also to VCL GUI API if it is possible. Thanks.
Regards,
•
•
Join Date: Aug 2009
Posts: 55
Reputation:
Solved Threads: 0
Dear firstPerson,
>>I like that comparison, younghc, even though your code is not easy
to follow. Its pretty neat.
Thanks for your kind words.
If there is anything in my codes which need explanation, please do not hesitate to ask. Admittedly, I look forward to be of service to this forum, from which I have been receiving invaluable assistance, which enabled me to jumpstart in learning C++ programming.
Remember...
"Ask and you will receive.
Seek and you will find;
knock and it will be opened to you."
(adapted).
This forum is living proof of the veracity of the above statements, and I am proud of it. Keep it up.
Regards,
>>I like that comparison, younghc, even though your code is not easy
to follow. Its pretty neat.
Thanks for your kind words.
If there is anything in my codes which need explanation, please do not hesitate to ask. Admittedly, I look forward to be of service to this forum, from which I have been receiving invaluable assistance, which enabled me to jumpstart in learning C++ programming.
Remember...
"Ask and you will receive.
Seek and you will find;
knock and it will be opened to you."
(adapted).
This forum is living proof of the veracity of the above statements, and I am proud of it. Keep it up.
Regards,
"if there is anything in my codes which need explanation, please do not hesitate to ask"
I don't mean I can't follow the code, I mean its not cleanly written.
And just when you thought there isn't another way :
I don't mean I can't follow the code, I mean its not cleanly written.
And just when you thought there isn't another way :
C++ Syntax (Toggle Plain Text)
#include<iostream> #include<cmath> #include<limits> using namespace std; typedef double data_type ; data_type Approx(data_type num) { int deg = 10; data_type cpy = num; while(cpy > 9) { cpy/=10; deg++; }; data_type i = num / deg; while(num < i*i) i-= unsigned long(1 + log(num)); if( i < 1) i = 0; for( ; i <= num; i++) { //power of 2 ? if(i * i == num) return i; //return closest int approxment else if( i * i > num) return i - 1; } return i-1; } inline data_type Avg(data_type X, data_type Y) { return (X+Y)/2.0; } data_type SquareRootOf(data_type Num, unsigned int precision = 30) { //check for default precision = 10; precision = precision < 10 ? 10 : precision; data_type X = data_type(Approx(Num)); if(X*X == Num) return X; data_type average = 0; while(precision--) { data_type Y = Num/X; average = Avg(Y,X); if(average * average == Num) return average; else X = average; } return average; } int main() { for(float i = 145; i < 164; i+=0.1) { cout.width(10); cout<<"(cmath,Mines) square root of : "<<i <<" is = "; cout.width(10); cout<<sqrt(data_type(i))<<"\t"<<SquareRootOf(data_type(i))<<endl; } return 0; }
Last edited by firstPerson; Sep 22nd, 2009 at 2:38 am.
I give up!
1) What word becomes shorter if you add a letter to it? [ Solved by : niek_e ]
2) What does this sequence equal to : (.5u - .5a)(.5u-.5b)(.5u-.5c) ...
3) What is the 123456789 prime numer? Oh wait another option , via Newton. Its a good approx.
It has similar logic as above, but the heat of the program relies on
calculus, which is done on paper.
It has similar logic as above, but the heat of the program relies on
calculus, which is done on paper.
C++ Syntax (Toggle Plain Text)
double Sqrt(double Num) { double i = 2; double Result = 0; unsigned int Precision = 10; for(int j = 0; j <Precision ; j++) { Result = i - (i*i - Num) / (2.0*i); i = Result; } return Result; }
I give up!
1) What word becomes shorter if you add a letter to it? [ Solved by : niek_e ]
2) What does this sequence equal to : (.5u - .5a)(.5u-.5b)(.5u-.5c) ...
3) What is the 123456789 prime numer?•
•
Join Date: Aug 2009
Posts: 55
Reputation:
Solved Threads: 0
Dear firstPerson,
>> .. Oh wait another option , via Newton. Its a good approx.
It has similar logic as above, but the heat of the program relies on
calculus, which is done on paper.
Your Newton algorithm is okay for small numbers. Above 6 consecutive numbers, accuracy of computation will be increasing less compared with other algorithms.
I suggest you plug your new sqrt function inside my program to see the comparative results. Anyway, nice try.
Regards,
>> .. Oh wait another option , via Newton. Its a good approx.
It has similar logic as above, but the heat of the program relies on
calculus, which is done on paper.
Your Newton algorithm is okay for small numbers. Above 6 consecutive numbers, accuracy of computation will be increasing less compared with other algorithms.
I suggest you plug your new sqrt function inside my program to see the comparative results. Anyway, nice try.
Regards,
![]() |
| Thread Tools | Search this Thread |
api array beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion count database delete desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive return sorting string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






