5

I want to round the complex and real part upto 2 decimal points. How can I do that in python?

angle = 2 * np.pi *2 c1 = complex(np.cos(angle),np.sin(angle)) c1 = round(c1,2) 
6
  • 2
    if you just want to display it rounded: f"{c1:.2}" or "{:.2}".format(c1). Commented Aug 9, 2019 at 13:44
  • 2
    complex(round(c1.real,2), round(c1.imag, 2)) Commented Aug 9, 2019 at 13:46
  • 2
    x = complex(round(x.real,2), round(x.imag,2)) Commented Aug 9, 2019 at 13:47
  • I have t use these complex numbers in a matrix. In order to read it easily I want to display it upto 2 decimal points Commented Aug 9, 2019 at 13:49
  • 1
    @Rick .2 rounds it to a precision of two (e.g., 1.23 is rounded to 1.2), not two decimal places. .2f could be considered instead. Commented Aug 9, 2019 at 13:49

3 Answers 3

4

You noted in a comment:

I have t use these complex numbers in a matrix. In order to read it easily I want to display it upto 2 decimal points

So how about modifying the printing of your data, rather than messing with their representation as data? You only need to set_printoptions with a formatter for complex numbers:

>>> import numpy as np >>> arr = np.random.rand(3,3) + 1j*np.random.rand(3,3) ... print(arr) [[0.44078748+0.29907718j 0.79358223+0.02234568j 0.20919567+0.34527526j] [0.05402969+0.24115898j 0.20941358+0.55299497j 0.29743888+0.32179154j] [0.60174937+0.9542182j 0.47197093+0.9202769j 0.41205623+0.27288905j]] >>> np.set_printoptions(formatter={'complex_kind': '{:.2f}'.format}) >>> print(arr) [[0.44+0.30j 0.79+0.02j 0.21+0.35j] [0.05+0.24j 0.21+0.55j 0.30+0.32j] [0.60+0.95j 0.47+0.92j 0.41+0.27j]] 
Sign up to request clarification or add additional context in comments.

Comments

3

I think you can use the around function from numpy:

import numpy x= complex(1.2345, 1.2345) numpy.around(x, 2) # (1.23+1.23j) 

Comments

0

For compact output:

np.set_printoptions(precision=2, suppress=True) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.