Home > front end >  Getting NaN when summing values in list with a for loop python
Getting NaN when summing values in list with a for loop python

Time:05-25

I am trying to obtain this sum: enter image description here

But I have been having issues with the second term.

This is my code so far:

hbar = 1.05457e-34
kB_si = 1.380649e-23
T = 3500
path = 'C:\\Users\\valit\\'  #path to file
file = 'data_175_phonopy_.dat'


k,f = np.loadtxt(path  file, unpack=True)

f = f//1e-12 #to convert THz to Hz
# print(f)

nondeg = []
for i in f:
    if i not in nondeg:
        nondeg.append(i)

svib = 0
for i in range(len(nondeg)):
    svib = svib   (-kB_si * (math.exp((-hbar * nondeg[i])/(kB_si * T))) - (1/T) * hbar * nondeg[i] / (math.exp((hbar * nondeg[i])/(kB_si * T)) - 1)) #nan

print(svib)

When I print svib I get Nan with the following message:

nan
C:\Users\valit\svib_modes.py:45: RuntimeWarning: invalid value encountered in double_scalars
  svib =  svib - ((1/T) * hbar * nondeg[i] / (math.exp((hbar * nondeg[i])/(kB_si * T)) - 1))

I know the issue is the second term because I added the two terms separately, and the first one gives me a really small number. Do you have any suggestions on how to get rid of the NaN? I apologize if my question is really simple, but I have been stuck for a while and could not find a way to solve it.

Thank y'all in advance.

CodePudding user response:

There are likely values in your file that are not numbers and performing arithmatic operations on nan result in nan. i.e. nan * 3 == nan and nan 3 == nan.

If you just want to ignore the nan values in your file, and only operate on the numbers, you could just filter them out:

f = f[~numpy.isnan(f)]

Just make sure you do want to ignore the nan values and they're not there due to some problem you cannot safely ignore.

CodePudding user response:

There are several causes for this error, as stated in 'invalid value encountered in double_scalars' warning, possibly numpy. So it is very difficult to help you without the data.

However, I would recommend you to investigate if a division-by-zero is taking place, because it seems to be a common cause for this error.

Also, you're calculating a very long expression in one shot. I should say this is a very bad practice.

Instead, split your expression in smaller parts and calculate it step by step, doing the required validations before each step.

E.g, instead of:

x = a / b   c * d / e

it would be more rational to do something like:

if (b == 0):
  # raise error, or do something about it

x = a / b

if (e == 0):
  # raise error, or do something about it

x  = c * d / e
  • Related