1

While doing some code excercise, I observed unusual ouput caused by the sqrt funtion,

The code was,

#include<stdio.h>
#include<math.h>
int main()
{
    double l,b,min_r,max_r;
    int i;
    scanf("%lf %lf",&b,&l);
    printf("%lf %lf\n",sqrt(l*l+b*b),sqrt(b*b-l*l));
    return(0);
} 

Output:

4 5
6.403124 -nan

Why does this happenes.

oturan
  • 329
  • 3
  • 19
  • for printing a `double`, `%f` will suffice. – Sourav Ghosh Dec 15 '15 at 12:25
  • 2
    (4*4-5*5)=-9 which is less than 0. sqrt() of a negative number is not a real number. – Mukit09 Dec 15 '15 at 12:28
  • %f is not a problem here. @SouravGhosh – Mukit09 Dec 15 '15 at 12:29
  • 1
    http://stackoverflow.com/questions/13730188/reading-in-double-values-with-scanf-in-c @SouravGhosh – Mukit09 Dec 15 '15 at 12:36
  • 1
    I'm telling again... for double %f is enough. but in this post, %f isn't problem. The only problem was, he was trying to print square root of a negative number. @SouravGhosh – Mukit09 Dec 15 '15 at 12:37
  • and for @MukitChowdhury, please do read the [lastest comment on the accepted answer](http://stackoverflow.com/questions/13730188/reading-in-double-values-with-scanf-in-c#comment42275373_13730228) of the question you pointed. Thanks. – Sourav Ghosh Dec 15 '15 at 12:43
  • @DarkDust Just to let you know, I did not mean to be rude, at all. :) Cheers!! (Let's remove the comment chain...). – Sourav Ghosh Dec 15 '15 at 12:50

2 Answers2

6

Look at the numbers: b is 4 and l is 5. So b*b - l*l is -9. What's the square root of -9? It's an imaginary number, but sqrt doesn't support imaginary results, so the result is nan (not a number). It's a domain error. The solution: Don't pass negative arguments to sqrt.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
2

In your case, not validating the inputs cause the issue.

sqrt(b*b-l*l)

with b as 4 and l as 5 produces a -ve number, which is most possibly you don't want.

FWIW, root of a negative number needs imaginary part to be represented.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261