Question

Hi I'm trying to do some calculations with long doubles and I am getting INF from sqrt() function.

Code:

#include <math.h>
#include <stdio.h>

int main()
{
    long double bigNUMBER;
    long double p1,p2,p3;
    long double p4;

    p1 = 4.769547e+155;
    p2 = 1.012994e+170;
    p3 = 1.714812e+169;

    p4 = p1*p1 + p2*p2 + p3*p3;

    bigNUMBER = sqrt(p4);

    printf("product: %Lf\n\n", p4); // 1055562645989439942507809393771156765931135...

    printf("\n result %Lf\n\n", bigNUMBER); // INF

    return 0;
}

Thank you!

Was it helpful?

Solution

sqrt takes and returns a double. When you call it, your long double will be converted in a double which cannot store such a big number, and will thus get the value of infinity.

Use sqrtl that takes and returns a long double.

OTHER TIPS

sqrt will return INFINITY when the argument is INFINITY as well; e.g.:

#include <stdio.h>
#include <math.h>
int main()
{
  printf("%g %g\n", INFINITY, sqrt(INFINITY));
  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top