# Comparing Two Arrays Using A If Loop

## 05 October 2019 - 1 answer

I am trying to compare if one array is greater then the other array using a IF statement.

``````from scipy.stats import laplace
from pylab import hist, title
from numpy import random

n = 10000

r = laplace.rvs(size=n)
normal = random.random(n)
new = r/normal

naccept = 0

if (new > normal):
naccept = naccept + 1
else:
pass

print('Acceptance fraction: ', naccept/n)

``````

I get the following error

``````

File "<ipython-input-64-b66ee75060af>", line 14, in <module>
if (new > normal):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

``````

What am I missing because both arrays are float64 so they should compare and return the acceptance fraction.

With numpy, a boolean operation on an array results in a boolean array.

It seems that you would like to count the number of times an element in the new array is above its counterpart in the normal array. You were almost there: simply count the number of `True` elements in the boolean array `new > normal`:

``````from scipy.stats import laplace
import numpy as np

n = 10000

r = laplace.rvs(size=n)
normal = np.random.random(n)
new = r/normal

# this counts the number of "True" (1) in the array (`False` is 0)
naccept = np.sum(new > normal)

print('Acceptance fraction: ', naccept/n)
``````

yields:

``````Acceptance fraction:  0.3754
``````