我有一个非常简单的问题。我想将1e-6
到10e-6
的间隔分成十个值,并将它们附加到列表中。因此,我在下面编写了程序,
start_value = 1e-6
stop_value = 10e-6
step_value = 10
step = (stop_value-start_value)/(step_value-9)
current_list = [start_value]
last_value = start_value
for i in range(step_value-1):
current_list.append(last_value + step)
last_value = last_value + step
print(current_list)
我得到以下结果,
[1e-06, 2e-06, 3e-06, 4e-06, 4.9999999999999996e-06, 5.999999999999999e-06, 6.999999999999999e-06, 8e-06, 9e-06, 1e-05].
当然,数字4.999999999e-6
和6.999999999e-6
应该分别为5e-06
和7e-06
。为此,我使用了round(**number** ,11)
方法。
start_value = 1e-6
stop_value = 10e-6
step_value = 10
step = (stop_value-start_value)/(step_value-9)
current_list = [start_value]
last_value = start_value
for i in range(step_value-1):
current_list.append(round(last_value + step, 11))
last_value = last_value + step
print(current_list)
还有另一种方法吗?
答案 0 :(得分:1)
您可以看一下fractions
模块:
import fractions
start_value = fractions.Fraction(1, 1000000)
stop_value = fractions.Fraction(10, 1000000)
step_value = 10
step = fractions.Fraction(stop_value-start_value, (step_value - 1))
current_list = []
for i in range(step_value):
current_list.append(start_value + i * step)
默认输出维护Fraction
类型的列表:
print(current_list)
[Fraction(1, 1000000), Fraction(1, 500000), Fraction(3, 1000000), Fraction(1, 250000), Fraction(1, 200000), Fraction(3, 500000), Fraction(7, 1000000), Fraction(1, 125000), Fraction(9, 1000000), Fraction(1, 100000)]
但是将其转换为本地数据类型非常简单:
print([float(x) for x in current_list])
[1e-06, 2e-06, 3e-06, 4e-06, 5e-06, 6e-06, 7e-06, 8e-06, 9e-06, 1e-05]
答案 1 :(得分:0)
您可以使用numpy:
import numpy as np
np.arange(1,11,1)*1e-6
输出:
array([1.e-06, 2.e-06, 3.e-06, 4.e-06, 5.e-06, 6.e-06, 7.e-06, 8.e-06,
9.e-06, 1.e-05])