Home > Enterprise >  How to use a for loop to computer elements of an array?
How to use a for loop to computer elements of an array?

Time:11-02

`import numpy as np
import matplotlib.pyplot as plt
import scipy

c=299792458 #speed of light in nanometers per second
h=6.62607015e-34 #plank's constant in m^2 kg per s
kB=1.380649e-23 #Boltzmann's constant in m^2 kg per s^2 K
π=np.pi
    
def F(λ,n):
    return ((2*π*h*c**2)/λ**5)*(1/(np.exp((h*c)/(λ*kB*n))-1))

def integrand0(λ):
        return F(λ,10800)

T=np.linspace(3000,12000,46)

import scipy.integrate as integrate  

for n in T:
    def integrand(λ):
        return F(λ,n)
    mU=-2.5*(np.log10(integrate.quad(integrand,325e-9,395e-9))-np.log10(integrate.quad(integrand0,325e-9,395e-9)))
    print('T=',n,'mU=',mU[0])
    
    
print(mU[0])

I'm able to see what the different values of mU are for the different n, and checked this with other code, but when I try to print mU[0] outside of the for loop, I just get a scalar (the final value) instead of a list, how do I make sure the different values get binned into the elements of an array?

CodePudding user response:

Each iteration in the for-loop you have is overriding the previous mU. If you wish to access the intermediate values from the loop after the loop has been run, you'll need to store them before the value gets overwritten.

My understanding from your question is that you are looking to store each iterations result to a list that you can refer back to with an index. To do that you can use list.append(). See the documentation here.

You could use something like this

mUlist = []
for n in T:
    def integrand(λ):
        return F(λ,n)
    mU=-2.5*(np.log10(integrate.quad(integrand,325e-    9,395e)-9))np.log10(integrate.quad(integrand0,325e-9,395e-9)))
    mUlist.append(mU)    # Or mUlist.append(mU[0]) to store only the first value
    print('T=',n,'mU=',mU[0])
    
    
print(mUlist[0])

CodePudding user response:

every for-loop iteration you rewrite mU name so after for-loop is worked you can get only mU that was created in the last for-loop iteration.
if you need to get all mU from every loop you need to create some list before the loop and append mU on every loop iteration to that list.
and finally you get what you need as that list.

  • Related