Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard
Alvaro wrote:sqrt() is implemented in hardware, probably using Newton-raphson. It's a mechanism that refines a previous guess for the square root.
...
using System;
namespace sqr
{
class MainClass
{
private static double O_(long o)
{
if(o==1)return(1);
double _o=0,_O=0;;
while(_O*_O<=o)
_o=++_O-((
_O)---_O++
);_o+=((o-
_o*_o)/(++
_o*_o---_o
*_o));
return(_o);
}
public static void Main()
{
long _o;
while((_o=Convert.ToInt32(Console.ReadLine()))!=0)
Console.WriteLine(O_(_o).ToString());
Console.Read();
}
}
}Darrylsh wrote:Alvaro wrote:sqrt() is implemented in hardware, probably using Newton-raphson. It's a mechanism that refines a previous guess for the square root.
...
Really!, that's interesting, are there other higher functions implented in hardware too?
How does one get access to these functions? asm?
I am working on a large interger class and this is one of the functions I need to implement. Is Newton-raphson what you'd recommend? My class uses an vector of integers to store base 1000 digits.
long sqrt(long num)
{
long i;
for(i=1;num>0;++i){
num=num-(2*i-1);
}
return i;
}Alvaro wrote:I guess the algorithm can be slightly modified so it works out. The problem I have with it is that it's really slow. Binary search would be much faster.
Wizard wrote:The square root of any number is somewhere between 0 and itself. So divide the number by two, and try that. If it's too high, go half lower, if too low, go half higher. Just like a binary search. You keep going, until you've got the precision you're looking for.
For example, sqrt(2)
low = 0, high = 2, mid = low+high /2 = 1
1*1 = 1, 1 < 2, so low = mid = 1, mid = low+high /2 = 1.5
1.5*1.5 = 2.25 too high, so high = 1.5, mid = low+high /2 = 1.25
... and so on, until you hit 1.414 or more precision if you so choose.
Return to Algorithms & Data Structures
Users browsing this forum: No registered users and 1 guest