Comparing Two Arrays Using A If Loop
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)
Acceptance fraction: 0.3754
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module