PYTHON   13

avewt.py

Guest on 6th June 2021 05:11:13 PM

  1. # weighted average and std dev
  2. #    Weighted average wtave.py
  3. import math
  4. from numpy import *
  5. import matplotlib.pyplot as plt
  6. import fpformat
  7. #-----------------------
  8. # function to compute weighted average
  9. # input data array and weight factors
  10. # output is weighted average
  11. def average (data,wt):
  12.       sumx=0.0; sumwt=0.0
  13.       sumx = dot(data,wt)
  14.       sumwt=sum(wt)
  15.       print 'sum(Wt*data), sum(wt)  ',sumx,sumwt
  16.       if sumwt==0: return -999
  17.       else: return sumx/sumwt
  18.  
  19. # read data from file: data, weights
  20. data=[]; num=[]; val=[]; wt=[]
  21. f=open("datawt.txt")    # data file
  22. k=0
  23. for line in f:
  24.         words=line.split()
  25.         valin=float(words[0])
  26.         wtin=float(words[1])
  27.         data.append(valin)
  28.         num.append(k+1)
  29.         val.append(valin)
  30.         wt.append(wtin)
  31.         print ' %3d   %8.2f   %8.2f ' %(k,data[k],wt[k])
  32.         k=k+1
  33. # ----------------------------
  34. ave=average(data,wt)
  35.  
  36. print ' Weighted ave= %8.2f '  %ave
  37. cav=fpformat.fix(ave,3)
  38. #-----------------------------
  39. #--------------
  40. plt.plot(num,val,'bo')
  41. plt.ylim(0,10)
  42. plt.xlim(0,10)
  43. plt.grid()
  44. plt.title('Wt Ave= '+cav )
  45. plt.show()
  46. #-----------------------------

Raw Paste


Login or Register to edit or fork this paste. It's free.