在下面的代码中,我试图用代码来进行编辑,以便以更像样的方式输出结果,如下所示。寻找一些帮助。
import numpy as np
import math
for p in range(10):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
print (p)
print (result)
Test = np.float64(2*np.sin(x/2)**2/x)
print (p)
print(Test)
给出以下结果:
0
0.459697694132
0
0.459697694132
1
0.0499583472197
1
0.0499583472197
2
0.00499995833347
2
0.00499995833347
3
0.000499999958326
3
0.000499999958333
4
4.99999996961e-05
4
4.99999999583e-05
5
5.0000004137e-06
5
4.99999999996e-06
6
5.00044450291e-07
6
5e-07
7
4.99600361081e-08
7
5e-08
8
0.0
8
5e-09
9
0.0
9
5e-10
但是,我试图以一种更恰当的方式输出结果。我该如何编辑代码,使其输出如下结果:
p Result Test
0 0.459697694132 0.459697694132
1 0.0499583472197 0.0499583472197
2 0.00499995833347 0.00499995833347
3 0.000499999958326 0.000499999958333
4 4.99999996961e-05 4.99999999583e-05
5 5.0000004137e-06 4.99999999996e-06
6 5.00044450291e-07 5e-07
7 4.99600361081e-08 5e-08
8 0.0 5e-09
9 1e-09 0.0 5e-10
答案 0 :(得分:1)
可以使用pandas DataFrame
vals = []
for p in range(10):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
test = np.float64(2*np.sin(x/2)**2/x)
vals.append((p, result, test))
然后
import pandas as pd
df = pd.DataFrame(vals, columns=['p', 'result', 'test'])
p result test
0 0 0.45969769 0.45969769
1 1 0.04995835 0.04995835
2 2 0.00499996 0.00499996
3 3 0.00050000 0.00050000
4 4 0.00005000 0.00005000
5 5 0.00000500 0.00000500
6 6 0.00000050 0.00000050
7 7 0.00000005 0.00000005
8 8 0.00000000 0.00000001
9 9 0.00000000 0.00000000
为了方便起见,您也可以使用np.vectorize
:
def func(p):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
test = np.float64(2*np.sin(x/2)**2/x)
return p, result, test
vals = np.vectorize(func)(np.arange(10))
pd.DataFrame(dict(zip(['p', 'result', 'test'], vals)))
答案 1 :(得分:0)
您的代码如下:
print("p Result Test")
for p in range(10):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
Test = np.float64(2*np.sin(x/2)**2/x)
print("{} {} {}".format(p, result, Test))
您可以使用f字符串(如果使用的是Python 3.6):
print("p Result Test")
for p in range(10):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
Test = np.float64(2*np.sin(x/2)**2/x)
print(f"{p} {result} {Test}")
答案 2 :(得分:0)
使用format
,但是很难在不添加新循环的情况下知道结果的最大长度。因此我可以做的是:
import numpy as np
import math
print("{:<3}".format("p"),"{:<23}".format("result"),"Test")
for p in range(10):
x=10.0**-p;
result = np.float64((1-np.cos(x))/x)
Test = np.float64(2*np.sin(x/2)**2/x)
print("{:<3}".format(p),"{:<23}".format(result),Test)
输出:
p result Test
0 0.45969769413186023 0.459697694132
1 0.049958347219741794 0.0499583472197
2 0.004999958333473664 0.00499995833347
3 0.0004999999583255033 0.000499999958333
4 4.999999969612645e-05 4.99999999583e-05
5 5.000000413701855e-06 4.99999999996e-06
6 5.000444502911705e-07 5e-07
7 4.9960036108132044e-08 5e-08
8 0.0 5e-09
9 0.0 5e-10
[Finished in 0.3s]