## sqrt()

Discuss all kind of algorithms and data structures from their mathematical and programming sides.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Yay! This works nicely:
[syntax="cpp"]#include <iostream>

double sqr(double num,double tol) {
double hi=num,lo=0.0,m;
while(lo<hi) {
m=(double)(lo+hi)/2.0;
if(m*m>=num-tol&&m*m<=num+tol)
return m;
else if(m*m<num) lo=m;
else hi=m;
}
return 0.0;
}

int main() {
std::cout<<sqr(25,0.000005);
std::cin.get();
}[/syntax]
If it wasn't for C, we would be using BASI, PASAL and OBOL.

tomcant

Posts: 3101
Joined: Tue Sep 23, 2003 1:56 am
Location: Colchester, UK

I'm still getting 6 for 25

just kiddin

Darryl

Posts: 1342
Joined: Wed Sep 01, 2004 10:50 am
Location: Cayman Islands

Code: Select all
`if (fabs(m*m - num) < eps) return m;`

for some really small value of eps. try giving it a value of 0.00001 or something.

edit: ok, nevermind. Solve your own problems, see if I care

Wizard

Posts: 3226
Joined: Mon Sep 22, 2003 4:52 pm
Location: ON, CA

Darryl wrote:maybe hmily thought that was a solution for getting sqrt.

I tried it out and it gives 6 for sqrt of 25, so I guess it needs more work

D

the code have something wrong.I have modiflied it:
Code: Select all
`nt i; long sqrt(long num) long i;  for(i=0;num>0;++i){      num=num-(2*i+1);  } return i;}`

hmily

Posts: 4
Joined: Wed Jan 12, 2005 3:50 am

hmily, your version only works for the square numbers.

I might keep my version and stick it in some library I havn't decided to make yet.
If it wasn't for C, we would be using BASI, PASAL and OBOL.

tomcant

Posts: 3101
Joined: Tue Sep 23, 2003 1:56 am
Location: Colchester, UK

tomcant wrote:hmily, your version only works for the square numbers.

I might keep my version and stick it in some library I havn't decided to make yet.

hehe,but Doe only want a long return sqrt(),so I think mine is better

hmily

Posts: 4
Joined: Wed Jan 12, 2005 3:50 am

hmily wrote:hehe,but Doe only want a long return sqrt(),so I think mine is better

Sorry to dig this up, but hmily, this is so blatantly better:
[syntax="cpp"]double sqr(double num,double tol=.000001) {
double hi=num,lo=0,m;
while(lo<hi) {
m=(lo+hi)/2;
if(m*m>num+tol) hi=m;
else if(m*m<num-tol) lo=m;
else return m;
} return 0;
}[/syntax]

I just had to post that

: Thats my `fast as I can make it' version. Thats the reason I'm posting it.
If it wasn't for C, we would be using BASI, PASAL and OBOL.

tomcant

Posts: 3101
Joined: Tue Sep 23, 2003 1:56 am
Location: Colchester, UK

Previous

### Who is online

Users browsing this forum: Google [Bot] and 0 guests