Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

python - How to round up a complex number?

How can I round up a complex number (e.g. 1.9999999999999998-2j) as 2-2j?

When I tried using

print(round(x,2))

it showed

Traceback (most recent call last):
  File "C:Python34FFT.py", line 22, in <module>
    print(round(x,2))
TypeError: type complex doesn't define __round__ method
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Round real part and imaginary part separately and combine them:

>>> num = 1.9999999999999998-2j
>>> round(num.real, 2) + round(num.imag, 2) * 1j
(2-2j)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...