Use cmath functions when calculations involve complex values.
What It Does and Why It Matters
cmath accepts complex arguments and implements trigonometric, exponential, logarithmic, square-root, polar, and rectangular coordinate utilities. Many functions may return complex results even if the imaginary component is zero; math is intended for real-number input.
For real-valued inputs whose domain excludes a negative value, cmath may return a valid complex answer.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import cmath
number = -4
print(cmath.sqrt(number))
print(cmath.phase(1j))
How the Code Works
- The imports make these standard-library tools available: cmath.
- The name number receives the value of -4. Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
2j
1.5707963267948966
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
Second Example: Compare Two Cases
Use a different input or a related operation to observe an important difference. The two examples help separate the general rule from one particular result.
import cmath
print(cmath.sqrt(-9))
Expected output:
3j
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Convert a complex value between rectangular and polar representation.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Trying to pass a complex input to math.sqrt() rather than using cmath.sqrt().
- Checking only the easiest input and missing a relevant error or boundary case.
Key Takeaways
- Use cmath functions when calculations involve complex values.
- cmath accepts complex arguments and implements trigonometric, exponential, logarithmic, square-root, polar, and rectangular coordinate utilities.
- Convert a complex value between rectangular and polar representation.