此列表应将x [50]设为零,并且两边要对称,但由于我认为是舍入误差,因此它稍微偏离中心。如何修改代码以避免这种情况?
谢谢!
import numpy as np
L=2*np.pi
s=101
ds=L/(s-1)
svals=np.arange(1,101)
x=[0]
x[0:s]=((svals-1)*ds)-L/2
print(x)
答案 0 :(得分:1)
从浮点运算中获得精确的输出可能很棘手,也很棘手。您可以使用np.linspace
获取所需的列表:
x = np.linspace(-np.pi, 0, num=51)
x = np.concatenate([x, np.linspace(x[-1] - x[-2], np.pi, num=50)])
print(x)
输出:
[-3.14159265 -3.0787608 -3.01592895 -2.95309709 -2.89026524 -2.82743339
-2.76460154 -2.70176968 -2.63893783 -2.57610598 -2.51327412 -2.45044227
-2.38761042 -2.32477856 -2.26194671 -2.19911486 -2.136283 -2.07345115
-2.0106193 -1.94778745 -1.88495559 -1.82212374 -1.75929189 -1.69646003
-1.63362818 -1.57079633 -1.50796447 -1.44513262 -1.38230077 -1.31946891
-1.25663706 -1.19380521 -1.13097336 -1.0681415 -1.00530965 -0.9424778
-0.87964594 -0.81681409 -0.75398224 -0.69115038 -0.62831853 -0.56548668
-0.50265482 -0.43982297 -0.37699112 -0.31415927 -0.25132741 -0.18849556
-0.12566371 -0.06283185 0. 0.06283185 0.12566371 0.18849556
0.25132741 0.31415927 0.37699112 0.43982297 0.50265482 0.56548668
0.62831853 0.69115038 0.75398224 0.81681409 0.87964594 0.9424778
1.00530965 1.0681415 1.13097336 1.19380521 1.25663706 1.31946891
1.38230077 1.44513262 1.50796447 1.57079633 1.63362818 1.69646003
1.75929189 1.82212374 1.88495559 1.94778745 2.0106193 2.07345115
2.136283 2.19911486 2.26194671 2.32477856 2.38761042 2.45044227
2.51327412 2.57610598 2.63893783 2.70176968 2.76460154 2.82743339
2.89026524 2.95309709 3.01592895 3.0787608 3.14159265]
分两步制作,以避免在linspace跨越0时出现数值误差。如果x
一步制作为
x = np.linspace(-np.pi, np.pi, 101)
然后,x[50]
的值为4.440892098500626e-16
,而不是x[50]
为预期的0
。