格式化复数

发布于 2024-12-09 19:18:51 字数 151 浏览 1 评论 0原文

对于我的一个课程中的一个项目,我们必须输出最多五位小数的数字。输出可能是一个复数,而我无法弄清楚如何输出具有五位小数的复数。对于浮点数,我知道它只是:

print "%0.5f"%variable_name

复数有类似的东西吗?

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 how to output a complex number with five decimal places. For floats I know it is just:

print "%0.5f"%variable_name

Is there something similar for complex numbers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小草泠泠 2024-12-16 19:18:51

您可以使用 str.format() 方法执行如下所示的操作:

>>> n = 3.4+2.3j
>>> n
(3.4+2.3j)
>>> '({0.real:.2f} + {0.imag:.2f}i)'.format(n)
'(3.40 + 2.30i)'
>>> '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n)
'(3.40 + 2.30i)'

为了使其正确处理正虚部和负虚部,您将需要(甚至更)复杂的格式化操作:

>>> n = 3.4-2.3j
>>> n
(3.4-2.3j)
>>> '({0:.2f} {1} {2:.2f}i)'.format(n.real, '+-'[n.imag < 0], abs(n.imag))
'(3.40 - 2.30i)'

更新 - 更简单的方法

尽管您不能使用字符串格式化运算符%f用作复数的表示类型:

n1 = 3.4+2.3j
n2 = 3.4-2.3j

try:
    print('test: %.2f' % n1)
except Exception as exc:
    print('{}: {}'.format(type(exc).__name__, exc))

输出:

TypeError: float argument required, not complex

但是,您可以通过以下方式将其与复数一起使用str.format() 方法。这没有明确记录,但由 格式规范迷你语言文档只是说:

'f'  定点。将数字显示为定点数。默认精度为 6

。 。 .所以很容易被忽视。
具体而言,以下内容在 Python 2.7.14 和 3.4.6 中均有效:

print('n1: {:.2f}'.format(n1))
print('n2: {:.2f}'.format(n2))

输出:

n1: 3.10+4.20j
n2: 3.10-4.20j

这并不能为您提供我原来答案中的代码所提供的完全控制,但它肯定更加简洁(并且可以处理正数和负数自动虚部)。

更新 2 - f-strings

格式化字符串文字(又名f-strings)是在Python 3.6中添加的,这意味着在该版本或更高版本中也可以这样做:

print(f'n1: {n1:.2f}')  # -> n1: 3.40+2.30j
print(f'n2: {n2:.3f}')  # -> n2: 3.400-2.300j

在Python 3.8中。 0,支持= 说明符 已添加到 f 字符串,允许您编写:

print(f'{n1=:.2f}')  # -> n1=3.40+2.30j
print(f'{n2=:.3f}')  # -> n2=3.400-2.300j

You could do it as is shown below using the str.format() method:

>>> n = 3.4+2.3j
>>> n
(3.4+2.3j)
>>> '({0.real:.2f} + {0.imag:.2f}i)'.format(n)
'(3.40 + 2.30i)'
>>> '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n)
'(3.40 + 2.30i)'

To make it handle both positive and negative imaginary portions properly, you would need a (even more) complicated formatting operation:

>>> n = 3.4-2.3j
>>> n
(3.4-2.3j)
>>> '({0:.2f} {1} {2:.2f}i)'.format(n.real, '+-'[n.imag < 0], abs(n.imag))
'(3.40 - 2.30i)'

Update - Easier Way

Although you cannot use f as a presentation type for complex numbers using the string formatting operator %:

n1 = 3.4+2.3j
n2 = 3.4-2.3j

try:
    print('test: %.2f' % n1)
except Exception as exc:
    print('{}: {}'.format(type(exc).__name__, exc))

Output:

TypeError: float argument required, not complex

You can however use it with complex numbers via the str.format() method. This isn't explicitly documented, but is implied by the Format Specification Mini-Language documentation which just says:

'f'  Fixed point. Displays the number as a fixed-point number. The default precision is 6.

. . .so it's easy to overlook.
In concrete terms, the following works in both Python 2.7.14 and 3.4.6:

print('n1: {:.2f}'.format(n1))
print('n2: {:.2f}'.format(n2))

Output:

n1: 3.10+4.20j
n2: 3.10-4.20j

This doesn't give you quite the control the code in my original answer does, but it's certainly much more concise (and handles both positive and negative imaginary parts automatically).

Update 2 - f-strings

Formatted string literals (aka f-strings) were added in Python 3.6, which means it could also be done like this in that version or later:

print(f'n1: {n1:.2f}')  # -> n1: 3.40+2.30j
print(f'n2: {n2:.3f}')  # -> n2: 3.400-2.300j

In Python 3.8.0, support for an = specifier was added to f-strings, allowing you to write:

print(f'{n1=:.2f}')  # -> n1=3.40+2.30j
print(f'{n2=:.3f}')  # -> n2=3.400-2.300j
勿忘初心 2024-12-16 19:18:51

字符串格式化操作 - 即模数 (%) 运算符) -
也不是较新的 str.format() 格式字符串语法< /a> 支持复杂类型。
但是,可以直接调用所有内置数字类型的 __format__ 方法。
这是一个示例:

>>> i = -3 # int
>>> l = -33L # long (only Python 2.X)
>>> f = -10./3 # float
>>> c = - 1./9 - 2.j/9 # complex
>>> [ x.__format__('.3f') for x in (i, l, f, c)]
['-3.000', '-33.000', '-3.333', '-0.111-0.222j']

请注意,这也适用于负虚部。

Neither String Formatting Operations - i.e. the modulo (%) operator) -
nor the newer str.format() Format String Syntax support complex types.
However it is possible to call the __format__ method of all built in numeric types directly.
Here is an example:

>>> i = -3 # int
>>> l = -33L # long (only Python 2.X)
>>> f = -10./3 # float
>>> c = - 1./9 - 2.j/9 # complex
>>> [ x.__format__('.3f') for x in (i, l, f, c)]
['-3.000', '-33.000', '-3.333', '-0.111-0.222j']

Note, that this works well with negative imaginary parts too.

∝单色的世界 2024-12-16 19:18:51

对于此类问题,Python 文档应该是您的第一站。具体来说,请查看有关字符串格式化的部分。它列出了所有字符串格式代码;没有复数的。

您可以做的是使用 x.realx.imag 分别格式化数字的实部和虚部,并在 a + bi 中打印出来 形式。

For questions like this, the Python documentation should be your first stop. Specifically, have a look at the section on string formatting. It lists all the string format codes; there isn't one for complex numbers.

What you can do is format the real and imaginary parts of the number separately, using x.real and x.imag, and print it out in a + bi form.

临风闻羌笛 2024-12-16 19:18:51
>>> n = 3.4 + 2.3j
>>> print '%05f %05fi' % (n.real, n.imag)
3.400000 2.300000i
>>> n = 3.4 + 2.3j
>>> print '%05f %05fi' % (n.real, n.imag)
3.400000 2.300000i
故事还在继续 2024-12-16 19:18:51

从 Python 2.6 开始,您可以定义自己的类的对象如何响应格式字符串。因此,您可以定义一个可以格式化的complex子类。下面是一个示例:

>>> 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).'

此类对象的行为与复数完全相同,只是它们占用更多空间且运行速度更慢;读者要小心。

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.

段念尘 2024-12-16 19:18:51

看看这个:

np.set_printoptions(precision=2)  # Rounds up to 2 decimals all float expressions

我已经成功打印了我的complexfloat的表达式:

# Show poles and zeros
print( "zeros = ", zeros_H , "\n")
print( "poles = ", poles_H )

out before:

zeros =  [-0.8       +0.6j -0.8       -0.6j -0.66666667+0.j ] 

poles =  [-0.81542318+0.60991027j -0.81542318-0.60991027j -0.8358203 +0.j        ]

out after:

zeros =  [-0.8 +0.6j -0.8 -0.6j -0.67+0.j ] 

poles =  [-0.82+0.61j -0.82-0.61j -0.84+0.j  ]

Check this out:

np.set_printoptions(precision=2)  # Rounds up to 2 decimals all float expressions

I've successfully printed my complexfloat's expressions:

# Show poles and zeros
print( "zeros = ", zeros_H , "\n")
print( "poles = ", poles_H )

out before:

zeros =  [-0.8       +0.6j -0.8       -0.6j -0.66666667+0.j ] 

poles =  [-0.81542318+0.60991027j -0.81542318-0.60991027j -0.8358203 +0.j        ]

out after:

zeros =  [-0.8 +0.6j -0.8 -0.6j -0.67+0.j ] 

poles =  [-0.82+0.61j -0.82-0.61j -0.84+0.j  ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文