gpt4 book ai didi

python - 修复函数的奇异性

转载 作者:行者123 更新时间:2023-11-28 19:40:51 25 4
gpt4 key购买 nike

假设你有一个像

这样的函数
F = lambda x: sin(x)/x

计算 F(0.0) 会导致被零除警告,并且不会给出 1.0 的预期结果。是否可以编写另一个函数 fix_singularity 将其应用于上述函数时给出所需的结果,以便

fix_singularity(F)(0.0) == 1.0

或者正式地fix_singularity应该通过以下测试:

import numpy as np

def test_fix_singularity():

F = lambda x: np.sin(x)/x

x = np.array((0.0, pi))

np.testing.assert_array_almost_equal( F(x), [nan, 0] )

np.testing.assert_array_almost_equal( fix_singularity(F)(x), [1, 0] )

一种可能的实现方式是

def fix_singularity(F):
""" Fix the singularity of function F(x) """

def L(x):
f = F(x)
i = np.isnan(f)
f[i] = F(x[i] + 1e-16)
return f

return L

有更好的方法吗?

编辑:另外我怎样才能抑制警告:

Warning: invalid value encountered in divide

最佳答案

numpy 有一个 sinc() 函数,它是函数的规范化形式,即

F = lambda x: sin(pi*x) / (pi*x)

它正确处理了 x == 0.0 的情况,

In [16]: x = numpy.linspace(-1,1,11)

In [17]: print x
[-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ]

要“非规范化”,

In [22]: s = numpy.sinc(x/numpy.pi)

In [23]: print s.round(2)
[ 0.84 0.9 0.94 0.97 0.99 1. 0.99 0.97 0.94 0.9 0.84]

关于python - 修复函数的奇异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com