C library - creal() function



The C complex library creal() function is typically used to extract the real part of the complex number. A complex number is composed by two components: a real and an imaginary (imag) parts.

If the real part is of the "float" type, we can use crealf() to get real part, and For long double, use creall().

Syntax

Following is the C library syntax of creal() function −

double creal( double complex z );

Parameters

This function accepts a single parameter −

  • Z − It represent a complex number.

Return Value

This function returns the real part of the complex number(z).

Example 1

Following is the basic c program to demonstrate the use of creal() to obtain the real part of the complex number(z).

#include <stdio.h>
#include <complex.h>
int main(void){
   double complex z = 1.0 + 2.0 * I;
   printf("The real part of z: %.1f\n", creal(z));
}

Output

Following is the output −

The real part of z: 1.0

Example 2

Let's see another example, we use the creal() function to obtain the real part of the generated complex number.

#include <stdio.h>
#include <complex.h>

int main() {
   double real = 3.0;
   double imag = 4.0;

   // Use the CMPLX function to create complex number
   double complex z = CMPLX(real, imag);

   printf("The complex number is: %.2f + %.2fi\n", creal(z), cimag(z));

   // obtain the real part
   // use creal()
   printf("The real part of z: %.1f\n", creal(z));

   return 0;
}

Output

Following is the output −

The complex number is: 3.00 + 4.00i
The real part of z: 3.0

Example 3

The below example of creal() function will demonstrate how to use it with complex numbers.

#include <stdio.h>
#include <complex.h>

int main(void) {
   double complex z = 10.0 + 5.0 * I;
   // Get the real part 
   double realNum = creal(z);
   // Print the result
   printf("The Complex number: %.2f + %.2fi\n", creal(z), cimag(z));
   printf("The Real part: %.2f\n", realNum);
   return 0;
}

Output

Following is the output −

The Complex number: 10.00 + 5.00i
The Real part: 10.00
c_library_complex_h.htm
Advertisements