Formatting Complex Numbers

前端 未结 5 636
粉色の甜心
粉色の甜心 2020-12-10 11:30

For a project in one of my classes we have to output numbers up to five decimal places.It is possible that the output will be a complex number and I am unable to figure out

5条回答
  •  感情败类
    2020-12-10 12:09

    As of Python 2.6 you can define how objects of your own classes respond to format strings. So, you can define a subclass of complex that can be formatted. Here's an example:

    >>> class Complex_formatted(complex):
    ...     def __format__(self, fmt):
    ...         cfmt = "({:" + fmt + "}{:+" + fmt + "}j)"
    ...         return cfmt.format(self.real, self.imag)
    ... 
    >>> z1 = Complex_formatted(.123456789 + 123.456789j)
    >>> z2 = Complex_formatted(.123456789 - 123.456789j)
    >>> "My complex numbers are {:0.5f} and {:0.5f}.".format(z1, z2)
    'My complex numbers are (0.12346+123.45679j) and (0.12346-123.45679j).'
    >>> "My complex numbers are {:0.6f} and {:0.6f}.".format(z1, z2)
    'My complex numbers are (0.123457+123.456789j) and (0.123457-123.456789j).'
    

    Objects of this class behave exactly like complex numbers except they take more space and operate more slowly; reader beware.

提交回复
热议问题