'How can I convert my python code with for loop into the code with while loop?
def H(f, a, b,samples,M):
c = np.zeros((M, samples))
d = a+(b-a)*np.random.random(size=(M))
for n in range(samples):
c[:,n]=g(d)
e = a + (b-a)*np.random.random(size=(M))
f = w(e)/w(d)
bigger_1 = np.nonzero(f>1)[0]
f[bigger_1] = np.ones(len(bigger_1))
cond = f > np.random.random(size=(M))
d = e*cond+d*(1-cond)
c = convert_x_to_z(b)*c
h = np.sum(c,axis=1)/samples
return h, np.sum(h)/M
here is my original code
In the following ,it is my trivial but it cannot work properly
def H(f, a, b,samples,M):
c = np.zeros((M, samples))
d = a+(b-a)*np.random.random(size=(M))
i=0
while i < len((samples)):
n=samples[i]
i=i+1
c[:,n]=g(d)
e = a + (b-a)*np.random.random(size=(M))
f = w(e)/w(d)
bigger_1 = np.nonzero(f>1)[0]
f[bigger_1] = np.ones(len(bigger_1))
cond = f > np.random.random(size=(M))
d = e*cond+d*(1-cond)
c = convert_x_to_z(b)*c
h = np.sum(c,axis=1)/samples
return h, np.sum(h)/M
it says that TypeError: object of type 'int' has no len(). Can you guys help me to fix it?Thx!
Solution 1:[1]
Look at the difference between the two loops:
for n in range(samples):
vs
while i < len((samples)):
what type is samples? Good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Firefighting Physicist |
