python 3.x - np.sum is rounding values to the nearest integer (not wanted) -


(some of code has been removed, such plotting code, doesn't affect issue)

as title states, i'm having issue numpy's sum function rounding nearest integer.

in following code, create variable chisqrr using np.sum, works intended, giving value of 1.23727.... near bottom of code, have practically exact same code need find bunch of values 'chisqr' based on range of input values. 3 lines of interest are:

chisqr[i] = np.sum(((counts - fit_exp_nonlin(t, popt[0], mu[i], popt[2]))/yerr)**2) print(((counts - fit_exp_nonlin(t, popt[0], mu[i], popt[2]))/yerr)**2) print(chisqr[i]) 

where first 'print' line, without np.sum command, gives bunch of values (all of long decimals), however, once summed np.sum, exact integers, not possible. example, 1 array before it's summed is:

[ 0.2251407   0.25516322  0.90413181  1.08316468  7.40191331  0.00893473 1.94594874  0.24967999  2.58848903  1.39550592  0.06140513] 

and 'sum' gives array is:

16 

whereas if sum values manually, get

16.11947726 

again, full code follows:

# imports import numpy np import matplotlib import matplotlib.pyplot plt scipy.optimize import curve_fit import pylab  def main():     counts = np.array([0.72, 0.74, 0.82, 0.86, 1.18, 0.84, 1.14, 0.96, 1.44, 1.64, 1.76])     t = np.array([108.5, 99.0, 90.0, 81.0, 71.0, 58.0, 45.0, 35.5, 26.0, 13.0, 0])/10      xx = np.array(np.linspace(-1,max(t)+max(t)*0.1,500))     guess1 = 1.1914367     guess2 = 0.19740375     guess3 = 0.61534327     guess = (guess1, guess2, guess3)     popt, pcov = curve_fit(fit_exp_nonlin, t, counts, guess, maxfev=1000)         chisqrr = (np.sum(((counts - fit_exp_nonlin(t, *popt))/yerr)**2))/(len(t)-4)     pylab.xlim([-1,12])     print(chisqrr)      mu = np.array(np.linspace(popt[1] - .1,popt[1] + .1,100))     chisqr = np.array([0] * len(mu))     in range(len(mu)):         chisqr[i] = np.sum(((counts - fit_exp_nonlin(t, popt[0], mu[i], popt[2]))/yerr)**2)         print(((counts - fit_exp_nonlin(t, popt[0], mu[i], popt[2]))/yerr)**2)         print(chisqr[i])  def fit_exp_nonlin(t, a, b, c):     return a*np.exp(-b*t) + c  if __name__ == '__main__':     main() 

this has been bugging me quite while , can't seem figured out, appreciated.

thank you.

as norbert van nobelen stated in comments, fixed changing

chisqr = np.array([0] * len(mu)) 

to

chisqr = np.array([0] * len(mu), dtype='f') 

thank norbert!


Popular posts from this blog