-2

sorry i am a bit of a newbie with programming but I am getting a float division error in a simple loop which I am not sure how to rectify.

Here is a code in python 2.7

import random

N = 100
A = []
p = 0
q = 0

k = 1
while k<=N:
    x = random.random()
    if x<= 0.5:
        p+= 1
    else:
        q+=1
    y = p/q
    A.append(y)
    k+=1

Running this code gives a zero division error. which I am not able to rectify. Can anyone tell me how to rectify this?

  • You set 'q' to zero and after first random less or equal 0.5 you have division by zero - simple. – Artur Jun 28 '16 at 13:33
  • hey guys thanks for the help, what i figured out is that replacing y = p/q with y = p/(q+0.000001) solves the issue. Although it feels a bit like cheating, but it works! – shailesh mishra Jun 29 '16 at 13:51

2 Answers2

0

You are getting zero division error because of this code

if x <= 0.5:
    p+=1
else:
    q+=1
y= p/q

You have initialised q = 0 thus when while loop is run first time and if x <= 0.5 then p will be incremented but q will be equal to zero and in next step you are dividing p by q(which is zero). You need to put a check condition before performing division so that denominator is not zero. You can rectify it in following manner.

if x <= 0.5:
    p+=1
else:
    q+=1
if (q == 0):
    print "Denominator is zero"
else:
    y= p/q

This is just one solution since I don't know what you are trying to do in your code.

prattom
  • 1,625
  • 11
  • 42
  • 67
0

You can use numpy.nextafter(q, 1). This gives you the next floating-point value after q towards 1, which is very small number.

Maryam Bahrami
  • 1,056
  • 9
  • 18