小编Dän*_*dän的帖子

添加数字时,在python/numpy中浮动精度细分

我有一些问题,因为与numpy一起使用的数字真的很少.我花了几个星期的时间来追溯数值积分的常数问题,即当我在函数中添加浮点数时,float64精度会丢失.使用产品而不是总和执行数学上相同的计算会产生合适的值.

这是一个代码示例和结果图:

from matplotlib.pyplot import *
from numpy import vectorize, arange
import math

def func_product(x):
    return math.exp(-x)/(1+math.exp(x))

def func_sum(x):
    return math.exp(-x)-1/(1+math.exp(x))

#mathematically, both functions are the same

vecfunc_sum = vectorize(func_sum)
vecfunc_product = vectorize(func_product)

x = arange(0.,300.,1.)
y_sum = vecfunc_sum(x)
y_product = vecfunc_product(x)

plot(x,y_sum,    'k.-', label='sum')
plot(x,y_product,'r--',label='product')

yscale('symlog', linthreshy=1E-256)
legend(loc='lower right')
show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

正如您所看到的,相当低的总和值分散在零或正好为零,而多重值很好......

拜托,有人可以帮忙/解释一下吗?非常感谢!

python precision numpy

9
推荐指数
1
解决办法
3817
查看次数

标签 统计

numpy ×1

precision ×1

python ×1