numpy division with RuntimeWarning: invalid value encountered in double_scalars

后端 未结 2 1537
误落风尘
误落风尘 2020-12-07 18:06

I wrote the following script:

import numpy

d = numpy.array([[1089, 1093]])
e = numpy.array([[1000, 4443]])
answer = numpy.exp(-3 * d)
answer1 = numpy.exp(-3         


        
2条回答
  •  我在风中等你
    2020-12-07 18:56

    You can use np.logaddexp (which implements the idea in @gg349's answer):

    In [33]: d = np.array([[1089, 1093]])
    
    In [34]: e = np.array([[1000, 4443]])
    
    In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
    
    In [36]: log_res
    Out[36]: -266.99999385580668
    
    In [37]: res = exp(log_res)
    
    In [38]: res
    Out[38]: 1.1050349147204485e-116
    

    Or you can use scipy.special.logsumexp:

    In [52]: from scipy.special import logsumexp
    
    In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
    
    In [54]: res
    Out[54]: 1.1050349147204485e-116
    

提交回复
热议问题