请考虑以下代码:
0.1 + 0.2 == 0.3 -> false
Run Code Online (Sandbox Code Playgroud)
0.1 + 0.2 -> 0.30000000000000004
Run Code Online (Sandbox Code Playgroud)
为什么会出现这些不准确之处?
如何创建一个列表,其中包含我输入的两个值之间的值?例如,为11到16的值生成以下列表:
list = [11, 12, 13, 14, 15, 16]
Run Code Online (Sandbox Code Playgroud) range()
Python中是否有等效的浮点数?
>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
Run Code Online (Sandbox Code Playgroud) 文档基本上说range
必须完全像这个实现一样(对于正面step
):
def range(start, stop, step):
x = start
while True:
if x >= stop: return
yield x
x += step
Run Code Online (Sandbox Code Playgroud)
它还说它的论点必须是整数.这是为什么?如果step是float,那么这个定义也不是完全有效吗?
就我而言,我是特别的.需要一个range
接受float类型作为step
参数的函数.在Python中有没有,或者我需要实现自己的?
更具体一点:我如何以一种很好的方式将这个C代码直接翻译成Python(即不仅仅是通过while
-loop手动完成):
for(float x = 0; x < 10; x += 0.5f) { /* ... */ }
Run Code Online (Sandbox Code Playgroud) 在给定边界之间制作包含均匀间隔数字(不仅仅是整数)的任意长度列表的pythonic方法是什么?例如:
my_func(0,5,10) # ( lower_bound , upper_bound , length )
# [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ]
Run Code Online (Sandbox Code Playgroud)
请注意,该Range()
函数仅处理整数.还有这个:
def my_func(low,up,leng):
list = []
step = (up - low) / float(leng)
for i in range(leng):
list.append(low)
low = low + step
return list
Run Code Online (Sandbox Code Playgroud)
看起来太复杂了.有任何想法吗?
我试图使用0.01的步长(例如)从0循环到1.我该怎么做呢?该for i in range(start, stop, step)
只需要整数参数,以便花车将无法正常工作.
假设我想从0循环到100但是步长为1/2.如果你试试
for i in range(0, 100, 0.5):
whatever
Run Code Online (Sandbox Code Playgroud)
它调用一个错误,说步骤不能为0.是否有内置的方法来做这样的事情?
我正在使用Python 2.x.
所以想象一下,我想要从0到100循环,但跳过奇数(所以"两个两个").
for x in range(0,100):
if x%2 == 0:
print x
Run Code Online (Sandbox Code Playgroud)
这解决了它.但想象一下,我想跳两个数字吗?三个呢?不是有办法吗?
我知道有很简单的方法可以生成唯一随机整数列表(例如random.sample(range(1, 100), 10)
).
我想知道是否有一些更好的方法来生成一个独特的随机浮点列表,除了编写一个像一个范围的函数,但接受像这样的浮点数:
import random
def float_range(start, stop, step):
vals = []
i = 0
current_val = start
while current_val < stop:
vals.append(current_val)
i += 1
current_val = start + i * step
return vals
unique_floats = random.sample(float_range(0, 2, 0.2), 3)
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
有没有办法用Python在MATLAB中创建一系列数字,使用简单的语法,即不使用循环.例如:
MATLAB:
a = 1:0.5:10
给
a = [1 1.5 2 2.5 3 3.5 .... 9.5 10]