2015-03-19 45 views
-1

我在python上运行以下代码来打印nos。在为偶数浮动号:在Python中获取MemoryError

def float_range(begin,end,step): 
    i=begin-step 
    numbers=[] 

    while i!=end: 
     i=i+step 
     numbers.append(i) 
    return numbers  #returning the list 

a=2 
b=4 
c=.1 
for j in float_range(a,b,c): #calling function 
    print j 

和它给以下错误

Traceback (most recent call last): 
    File "C:\Users\b53659\Desktop\My python\float_range.py", line 13, in <module> 
    for j in float_range(a,b,c): 
    File "C:\Users\b53659\Desktop\My python\float_range.py", line 7, in float_range 
    numbers.append(i) 
MemoryError. 

但在上面的代码中指定,如果我更换范围

a=1 
    b=1000 
    c=1 

它给正确的输出即没有打印。从1到1000. 为什么会发生?在此先感谢

+0

使用十进制...... – YOU 2015-03-19 10:13:23

+0

http://blog.reverberate.org/2014/09/what-every-computer-programmer -should.html – RvdK 2015-03-19 10:20:25

+0

'而我<结束或使用'epsilon' – 2015-03-19 10:27:44

回答

0

代码中的主要缺陷是while condition !=

您正在查看是否i!=end。这里的步数是0.1,实际上是0.100000000000001。所以,当你到达最后一次迭代(按你的逻辑)

i = 3.9 + step = 4.000000001 

,你有end= 4.0i!=end

所以你while loops condition i!=end is True always和循环永续,并抛出内存不足的错误

我已经调试你代码并找到列表中的实际值。你可以从屏幕截图中看到4.0的值从来没有产生,而不是4。0000001获取生成 enter image description here

如你预期这个代码将工作:

def float_range(begin,end,step): 
    i=begin-step 
    numbers=[] 

    while i < end: 
     i=i+step 
     numbers.append(i) 
    return numbers  #returning the list 
2

问题是,您使用c=.1,它使计数器浮点。当循环获取到“端”(在float_range),我会像4.000000000013.9999999999998,因此它并不比等于整数4

有几个可能的解决方案:

  • 只使用整数(整数,而不是0.1)
  • 使用Python的定点数(在decimal.Decimal类)
  • 做,而不是i < end循环结束条件i!=end
1

你应该做这样的事情

def float_range(begin,end,step): 
    i = begin-step 
    numbers = [] 

    while i < end: 
     i += step 
     numbers.append(i) 
    return numbers  #returning the list 

for j in float_range(2,4,0.1): #calling function 
    print round(j, 2) 

这样你就可以确保循环时,它的上面end即使浮动不打确切的整数值停止。

我还做了两个除while i < end:以外的其他更改。您可以使用+=而不是i = i+step。我也将花车四舍五入,因为如果你不这样做,它会打印出像3.9000000000000017这样的东西。

我希望这会有所帮助。