Printing values of a certain order in Python

Question:

I have an array A and I want to print number of values which are of the order: 1e2 and also the specific values.

I present the current and expected outputs.

import numpy as np

A=np.array([ 4.22134987e+02,  4.22134987e+02,  4.22134987e+02,  4.22134987e+02,
        4.22134987e+02, -7.07598661e-11, -6.80734822e-11,  8.24084601e-11])

B=A[A==1e2]
print(B)

The current output is

[]

The expected output is

[5,4.22134987e+02]
Asked By: rajunarlikar123

||

Answers:

1e2 is 100.00

import numpy as np

A=np.array([ 4.22134987e+02,  4.22134987e+02,  4.22134987e+02,  4.22134987e+02,
        4.22134987e+02, -7.07598661e-11, -6.80734822e-11,  8.24084601e-11])

B=A[A>=1e2]  #or B=A[A>=100]
[len(B),*set(B)]

#output
[5, 422.134987]
Answered By: God Is One

You can use:

tol = 8  # tolerance
m = (1 <= A/1e2) & (A/1e2 < 10)
B = A[m]
B = (len(B), list(np.unique(B.round(tol))))

Output:

>>> B
(5, [422.134987])

>>> m
array([ True,  True,  True,  True,  True, False, False, False])
Answered By: Corralien

One option using transformation to log10, ceil and unique to get the values in the range [100-1000[

np.unique(A[np.ceil(np.log10(A)) == 2+1], return_counts=True)

Output: (array([422.134987]), array([5]))

Answered By: mozway

The "of the order" is relative, because of which one should specify how close to 1e2 is desired. One way amongst many to do that is to define a factor, say fac here, so that the range of (100./fac, 100*fac) will be accepted:

import numpy as np

A=np.array([ 4.22134987e+02,  4.22134987e+02,  4.22134987e+02,  4.22134987e+02,
        4.22134987e+02, -7.07598661e-11, -6.80734822e-11,  8.24084601e-11])

fac=5.
B=A[np.where((A<fac*1e2) & (A>1e2/fac))]
print('-'*50)
print('B: ', B)
print('-'*50)
print('count: ', len(B))
print('-'*50)
print('[count, set(B)]: ', [len(B),*set(B)])
print('-'*50)

Output:

--------------------------------------------------
B:  [422.134987 422.134987 422.134987 422.134987 422.134987]
--------------------------------------------------
count:  5
--------------------------------------------------
[count, set(B)]:  [5, 422.134987]
--------------------------------------------------
Answered By: learner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.