Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Inconsistent behavior when using float on complex number vs complex quantity #10010

Closed
@namurphy

Description

@namurphy

Description

Using float or numpy.float on a complex number results in a TypeError. Using float or numpy.float on that complex number represented as a dimensionless Quantity results in the real part being returned and a ComplexWarning being issued. The consequence is that code using complex numbers and complex quantities may behave differently, so it may be necessary to write separate code to handle complex numbers and complex quantities. Code that relies on the current behavior for quantities should instead use numpy.real.

Expected behavior

I would expect that using float or numpy.float on a complex number represented as a dimensionless Quantity would raise a TypeError also.

Actual behavior

Using float on a complex number multiplied with astropy.units.dimensionless_unscaled returns the real part while issuing a ComplexWarning.

Steps to Reproduce

>>> import numpy as np
>>> import astropy.units as u
>>> complex_number = 5 + 6j
>>> complex_quantity = complex_number * u.dimensionless_unscaled

>>> float(complex_number)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

>>> float(complex_quantity)  # would expect a TypeError for consistency
/media/Scratch/namurphy/envs/empty_for_astropy/lib/python3.8/site-packages/astropy/units/quantity.py:1077: ComplexWarning: Casting complex values to real discards the imaginary part
  return float(self.to_value(dimensionless_unscaled))
5.0

The TypeError came from this line in quantity.py.

System Details

Linux-3.10.0-957.27.2.el7.x86_64-x86_64-with-glibc2.10
Python 3.8.2 | packaged by conda-forge | (default, Mar  4 2020, 21:29:16) 
[GCC 7.3.0]
Numpy 1.18.1
astropy 4.1.dev703+g3c88b57e3
ModuleNotFoundError: No module named 'scipy'

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions