From: Phil Galbiati Newsgroups: comp.os.msdos.djgpp Subject: Re: sqrt() problem Date: Mon, 09 Dec 1996 19:37:08 -0800 Organization: Tektronix Lines: 84 Message-ID: <32ACDAE4.33FB@Tek.com> References: <32aa47fd DOT 8683086 AT nntp DOT southeast DOT net> <32AABA23 DOT 15FC AT cs DOT com> <32ab4462 DOT 73306026 AT nntp DOT southeast DOT net> <32AB49F3 DOT 65AF AT cornell DOT edu> NNTP-Posting-Host: philipga.cse.tek.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: murray AT southeast DOT net CC: "A. Sinan Unur" DJ-Gateway: from newsgroup comp.os.msdos.djgpp A. Sinan Unur wrote: > > Murray Stokely wrote: > > it seems sqrt is returning a realy > > weird number > ^^^^^ > no it is not. > > > > > s=sqrt((double)(r*r) - (double)(m*m)); > > // also used pow(x,2) - same result > > printf("%d\n",s); ^^^ You are attempting to print a double (8-byte floating point data) as a 4-byte decimal integer. > > // also used %i - same result > > > > r and m are integers (10 and 50), yet s keeps returning a huge > > negative number (should be like 51 or something) > > > > Murray Stokely ( murray AT southeast DOT net ) > > do you realize that 10*10 - 50*50 = -2400 and there is no real > number whose square will give you -2400? you are feeding sqrt > a totally invalid argument. GIGO (garbage-in-garbage-out). > the ansi standard states that "...a domain error occurs if the > argument is negative." elsewhere, it states that "On a domain > error, the function returns an implementation-defined value; > the value of the macro EDOM is stored in errno. The fact that he (Murray) got anything to print suggests to me that what he posted was *not* what he compiled, since sqrt()ing a negative number should cause a floating point exception (at least it does on my machine), and unless he has a handler for SIGFPE, his program would have crashed before printing the "huge negative number" he described. I *suspect* that he compiled: s = sqrt((double)(r*r) + (double)(m*m)); ^^^ Change the '-' to a '+', and fix the printf() statement and it should work better. If you make both changes it should print: 50.990195 Here's the whole program with changes hi-lited /********************* CUT HERE *******************/ #include #include int main () { double s; int r; int m; r = 10; m = 50; s = sqrt((double)(r*r) + (double)(m*m)); /* ^^^ */ printf("%lf\n",s); /* ^^^ */ return (0); } /********************* CUT HERE *******************/ Compile like this: gxx -ofoo foo.cpp Hope this helps. --Phil Galbiati ================================================= Any opinions expressed here reflect the ignorance of the author, NOT Tektronix. =================================================