sqrt or negative zero?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: sqrt or negative zero?

  1. #1
    Join Date
    Jan 2011
    Posts
    1

    Question 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

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,893

    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().

  3. #3
    Join Date
    Jan 2009
    Posts
    1,689

    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center