Advertisement

calculating square roots

Started by October 10, 2002 08:38 PM
16 comments, last by Samith 22 years, 4 months ago
how do calculators calculate square roots?? its just one of those things thats been bothering me for a while since i cant figure it out if anyone has a link to how its done or can tell me, ide love it :D oh and, by the way, ide also like to know how to calculate sine and cosine without a calculator
Sam Johnston (Samith)
This works:

double sqrt( double x ) {	float	y;	float	delta;	float	maxError;	if ( x <= 0 ) {		return 0;	}	// initial guess	y = x / 2;	// refine	maxError = x * 0.001;	do {		delta = ( y * y ) - x;		y -= delta / ( 2 * y );	} while ( delta > maxError || delta < -maxError );	return y;} 

It''s from the q3 code if you''re wondering. It looks complicated, but it''s not really if you break it down.
Advertisement
Would that be faster than the standard sqrt function? *just curious*

______________________________________________
(MSG_POST_DONE) ? InsertWittySignature() : ContinuePosting()

http://www.geocities.com/codeman_net/
- Hun Yen Kwoon
That is from the Q3 code so I''m sure it''s optimized all the way. The standard sqrt function probably looks something like that, anyhow, but I would just stick with the standard sqrt function since it''s already compiled into a library and everything.
Dont take this like I''m trying to call you a liar (as I am certainly not doing that) - but how did you get any chunk of the q3 source??
use Taylor

exp(x) = sum(k=0..inf) (x^k/k)
sin(x) = sum(k=0..inf) (-1)^k * x^(2k+1)/(2k+1)!
....

the sqrt funct is a bit harder. There isn''t one for sqrt(x)
only

(1+x)^a = 1+ax+(a(a-1)/2!)*x^2+(a(a-1)(a-2)/3!)*x^3+....

if you take a=1/2 you get sqrt(1+x)
Advertisement
quote:
Original post by Xori
Dont take this like I''m trying to call you a liar (as I am certainly not doing that) - but how did you get any chunk of the q3 source??

http://www.idsoftware.com/business/home/techdownloads/
[ PGD - The Home of Pascal Game Development! ] [ Help GameDev.net fight cancer ]
quote:
Originally posted by crossbow
The standard sqrt function probably looks something like that...
Not really - on the x86, it just uses FSQRT.
Newton and Taylor are the usual suspects.
One other way is Heron''s algorithm:
x(i+1) = ( x(i) + x/x(i) ) / 2
E8 17 00 42 CE DC D2 DC E4 EA C4 40 CA DA C2 D8 CC 40 CA D0 E8 40E0 CA CA 96 5B B0 16 50 D7 D4 02 B2 02 86 E2 CD 21 58 48 79 F2 C3
I''m gonna be picky about the q3a source heh

y -= delta / ( 2 * y );

you can replace (2*y) with y + y ... multiplications take quite a bit more clock cycles than additions.


I had a lot of ppl on here tell me that method was slower than what would be in the standard library...they could be wrong, though.
:: h0-0t ::

This topic is closed to new replies.

Advertisement