0

I have some python code here

Code:

 t = 1
 xt = array([ -1.,-1. ])

 xt[0] = theta[0][0]* P_all_States[t-1][0] + theta[1][0]*P_all_States[t-1][1]

 xt[1] = theta[0][1]* P_all_States[t-1][0] + theta[1][1]*P_all_States[t-1][1]

 P_all_States[t][0] = xt[0]
 P_all_States[t][1] = xt[1]
 print ("Added probability distribution for time t = " + str(t) + " to P_all_States")
 print P_all_States

Output:

Added probability distribution for time t = 1 to P_all_States [[0.6, 0.4], [0.62000000000000011, 0.38000000000000006], [-1.0, -1.0], [-1.0, -1.0], [-1.0, -1.0], [-1.0, -1.0]]

How can I get the floating point numbers to round to 2 sigficant digits?

These are all floats, so Im not looking to convert these to strings, I want them to remain as floats

Thanks

banditKing
  • 9,405
  • 28
  • 100
  • 157
  • 2
    related: [Pretty-printing of numpy.array](http://stackoverflow.com/q/2891790/4279), namely `np.set_printoptions(precision=2)` – jfs Oct 13 '12 at 20:06

3 Answers3

3

I am not sure what you mean, but if you mean how you can modify their value to exactly 0.62, etc. : this is not possible with floats, because of their nature. You could use decimals instead of floats to get around this issue. If you mean how to print the floats with only 2 decimals, use:

print '{:3.2f}'.format(somefloat)
John Peters
  • 1,177
  • 14
  • 24
2
>>> round(0.62000000000000011,2)
0.62
Zashas
  • 736
  • 4
  • 11
  • 1
    You should note that this doesn't actually result in the value `0.62`. `print decimal.Decimal(round(0.62000000000000011,2))` -> `0.61999999999999999555910790149937383830547332763671875`. – senderle Oct 13 '12 at 20:29
0

To convert the whole list, combine @Zashas answer with:

rounded = [ [round(a[0],2), round(a[1],2)] for a in P_all_States ]
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18