【问题标题】:np.sum is rounding values to the nearest integer (not wanted)np.sum 将值四舍五入到最接近的整数(不需要)
【发布时间】:2015-04-10 00:42:07
【问题描述】:

(部分代码已被删除,如绘图代码,不影响问题)

正如标题所述,我在使用 Numpy 的 sum 函数舍入到最接近的整数时遇到问题。

在下面的代码中,我使用 np.sum 创建了变量 chisqrR,它按预期工作,给我的值为 1.23727...。在代码的底部附近,我需要的代码几乎完全相同根据一系列输入值查找“chisqr”的一堆值。感兴趣的三行是:

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])

第一个“打印”行,没有 np.sum 命令,给出了一堆值(所有这些都是长小数),但是,一旦它们被 np.sum 求和,我总是得到精确的整数,这绝对不可能。例如,求和前的一个数组是:

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

它为该数组提供的“总和”是:

16

而如果我手动对这些值求和,我会得到

16.11947726

同样,完整的代码如下:

# Imports
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from 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))
    for i 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()

这已经困扰了我很长一段时间了,我似乎无法弄清楚,任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 您可以添加数据类型:np.sum(... , dtype=float)。可能会成功
  • 行得通!我不知道 np.array 默认为整数数据类型。谢谢!
  • @John - 值得一提的是,numpy 并不默认为整数数据类型。相反,它会尝试推断输入的类型。如果你传入一个浮点数序列,你会得到一个浮点数数组,同样,如果你传入一个整数序列,你会得到一个整数数组。 (混合类型的序列要么向上转换(例如,[0, 0.0] 将成为浮点数组),要么在任何项不是数字时转换为对象数组。)

标签: python-3.x numpy sum


【解决方案1】:

正如 Norbert van Nobelen 在 cmets 中所说,这已通过更改解决

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

到

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

谢谢诺伯特!

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多