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

1

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

2
>>> round(0.62000000000000011,2)
0.62

1 Comment

You should note that this doesn't actually result in the value 0.62. print decimal.Decimal(round(0.62000000000000011,2)) -> 0.61999999999999999555910790149937383830547332763671875.
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 ]

2 Comments

it is a list of list, so the above won' t do the job, need something like: rounded = [ [round(a[0],2), round(a[1],2)] for a in P_all_States ]
sorry - did not realize that. well, you corrected it. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.