-
January 31st, 2011, 01:04 PM
#1
sqrt or negative zero?
Hi,
I'm having a bit trouble with this equation:
sum = pow(cos(x),2) + pow(cos(y),2);
z = acos ( sqrt ( 1 - sum ) );
so when sum == 1, it should be sqrt(1-1) i.e. sqrt(0) which should be 0..
however I get an error as .. Nan..
a little help please.. how do i tell c++ that it is 0 not -0
-
January 31st, 2011, 01:21 PM
#2
Re: sqrt or negative zero?
Unfortunately floating point math is not exact. Therefore, it's possible that "sum" could be ever so slightly greater than 1, and therefore you would be trying to take the square root of an actual negative (not just -0).
One solution in this case would be to use fabs(1 - sum). Assuming that sum is never much more than 1, which it shouldn't be, this wouldn't change your answer too much but would ensure you never put a negative into the sqrt().
-
January 31st, 2011, 04:17 PM
#3
Re: sqrt or negative zero?
Yeah, the rounding errors must be pushing it to negative numbers. sqrt(-0) will return -0; Only negative numbers will go into imaginaries.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|