1

This is probably and easy one for you guys, but I couldn't find a definitive answer and I just want to be sure I'm not overlooking anything. I have an equation, which I know permits complex solutions, but I've programmed it in C using "double" and/or "float". Does C simply ignore the complex part if I don't use "complex" types? In other words, does it simply return the real part? Will it generate any errors by not using "complex"? Thanks.

ThatsRightJack
  • 721
  • 6
  • 29

2 Answers2

3

There is a 'complex' and an 'imaginary' data type in C. However, since it has only been a few years since it has been introduced, some of the old systems might not support it. So, its best to handle that kind of solutions explicitly.

If you are performing an illegal operation like sqrt(-1), then it will generate an error.

The following post most probably answers your queries better How to work with complex numbers in C?

Community
  • 1
  • 1
Python_user
  • 1,378
  • 3
  • 12
  • 25
2

The documentation for sqrt() (if you read it) tells you it returns a domain error.

You can find this out for yourself with a test case:

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

int main(int argc, char *argv[])
{
    double foo = -1.234;
    double foo_sqrt = sqrt(foo);
    if (errno == EDOM) {
        fprintf(stderr, "Error: EDOM - Mathematics argument out of domain of function (POSIX.1, C99)\n");
        return EXIT_FAILURE;
    }
    /* we never get here */
    fprintf(stdout, "sqrt(%f) = %f\n", foo, sqrt(foo));
    return EXIT_SUCCESS;
}

Then compile and run:

$ gcc -lm -std=c99 -Wall sqrt_test.c -o sqrt_test
$ ./sqrt_test
Error: EDOM - Mathematics argument out of domain of function (POSIX.1, C99)
$ echo $?
1
Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
  • Thanks Alex! If stackoverflow didn't exist, I would be forced to read the documentation (blah). I know many of you on here are VERY proficient at this stuff, so I thought a simple question wouldn't hurt ; ) Thanks again! – ThatsRightJack Jan 25 '15 at 07:04