Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Nan computation

Tags:

nan

numpy

Can someone help me with this? I'm trying to avoid nan value in my resulting List. because if p gets too close to zero, it is generating nans in my new list.

import random
import numpy as np
from numpy import log 


def Compute(ListA):
    NewListA = []
    p = random.random()
    for item in ListA:
        u=np.exp(-(float(item)/500)**1.2)
        y=500*((np.log(1/(u*(1-p))))**(1/1.2))
        while y == nan:
            continue
        else:
            y=500*((np.log(1/(u*(1-p))))**(1/1.2))
            NewListA.append(y)
    return NewListA

ListA = [2.00345, 0.004, 3.0876, 6.00034, 8.0777, 9.444, 0.0004, 11.000678]
print (Compute(ListA))
like image 789
Eric Enkele Avatar asked May 26 '26 18:05

Eric Enkele


1 Answers

Use if instead of while; and isnan instead of ==nan.

    if np.isnan(y):   #while y == nan:
        continue
    NewListA.append(y)   # don't need to repeat y calc?

You want to skip this item not some new iteration on y. When I used your syntax I got stuck in an infinite loop that I had to kill.

In [324]: for item in range(10):
     ...:     while item==5:
     ...:         continue
     ...:     else:
     ...:         print(item)
     ...:         
0
1
2
3
4
<infinite loop>

Your code doesn't get stuck because y==nan is always False.

Corrected iteration:

In [1]: alist=[]
In [2]: for item in range(10):
   ...:     if item==5:
   ...:         continue
   ...:     else:
   ...:         alist.append(item)

In [4]: alist
Out[4]: [0, 1, 2, 3, 4, 6, 7, 8, 9]

And alternative to the continue block.

for item ...
    y = ....
    if not np.isnan(y):
       newList.append(y)
like image 69
hpaulj Avatar answered May 30 '26 21:05

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!