Reputation: 43
The printed numbers are very long as it can be seen when we run the code. The numbers appended are too long and displaying them in a table like format is not possible with the current result. How do we append float with only 4 numbers after decimal directly for pn, u, v and a ?
y = 1/2
b = 1/4
u = []
v = []
t = []
p = [0,25,43.3013,50,43.3013,25,0,0,0,0,0,0]
a = []
pn = []
pn.append(0)
x = 0.0
for i in range(11):
z = 0.0 + x
t.append(z)
x = x + 0.1
m = 0.45594
k = 18
c = 0.2865
u.append(0)
v.append(0)
a.append((p[0]-c*v[0]-k*u[0])/m)
dt = 0.1
a1 =(m/(b*dt*dt)+y*c/(b*dt))
a2 = (m/(b*dt)+(y/b-1)*c)
a3 = (((1/(2*b))-1)*m + dt*((y/(2*b))-1)*c)
kn = k + a1
for i in range(len(t)-1):
pn.append(p[i+1]+ a1*u[i] + a2*v[i] + a3*a[i])
u.append(pn[i+1]/kn)
v.append(y*(u[i+1]-u[i])/(b*dt) + (1-y/b)*v[i] + dt* (1-y/(2*b))*a[i])
a.append((u[i+1]-u[i])/(b*dt*dt) - v[i]/(b*dt)-(1/(2*b)-1)*a[i])
print("ti\t\t"+"Pi\t\t"+"Pni\t\t"+"u''i\t\t"+"u'i\t\t"+"ui")
for i in range(len(t)):
print(t[i],p[i],pn[i],a[i],v[i],u[i])
Upvotes: 1
Views: 706
Reputation: 24420
Rounding numbers when you still need them for further calculations isn't a good idea since it can lead to numerical inaccuracies. Instead of rounding the numbers themselves you could consider formatting the numbers during printing. For example, to print the numbers in a nicely formatted table you could do something like
col_width = 10
ndecimals = 4
headers = ["time", "p", "pn", "a", "v", "u"]
data = [t, p, pn, a, v, u]
# print header
for tt in headers:
print(f'{tt:>{col_width}}', end='')
print()
print('-'*col_width*len(headers))
# print data
for fields in zip(*data):
for field in fields:
print(f'{field:{col_width}.{ndecimals}f}', end='')
print()
Result
time p pn a v u
------------------------------------------------------------
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
0.1000 25.0000 25.0000 48.5187 2.4259 0.1213
0.2000 43.3013 133.1779 64.3899 8.0714 0.6462
0.3000 50.0000 350.4197 34.3673 13.0092 1.7002
0.4000 43.3013 619.7712 -31.9927 13.1280 3.0071
0.5000 25.0000 819.2410 -106.0045 6.2281 3.9749
0.6000 0.0000 814.7317 -151.8705 -6.6657 3.9530
0.7000 0.0000 550.8590 -93.6138 -18.9399 2.6727
0.8000 0.0000 109.2240 -5.8938 -23.9153 0.5299
0.9000 0.0000 -346.0107 79.0077 -20.2596 -1.6788
1.0000 0.0000 -655.0597 131.5883 -9.7298 -3.1783
Upvotes: 1
Reputation: 28
Try this print
`print("{0:.4f}".format(t[i]),"{0:.4f}".format(p[i]),"{0:.4f}".format(pn[i]),
"{0:.4f}".format(a[i]),"{0:.4f}".format(v[i]),"{0:.4f}".format(u[i]))`
Upvotes: 1