gpt4 book ai didi

python : How to avoid numpy RuntimeWarning in function definition?

转载 作者:IT老高 更新时间:2023-10-28 20:56:50 27 4
gpt4 key购买 nike

我设计了一个简单的函数来返回一个数学函数,该函数可用于拟合实验数据。这些函数看起来很像以下:

def colecole_2(f,*p):
term1=p[0] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[1], p[2])))
term2=p[3] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[4], p[5])))
return p[6]*(1-abs( term1+ term2))

不幸的是,我遇到了 RunTimeWarnings 的问题:

RuntimeWarning: overflow encountered in power
RuntimeWarning: overflow encountered in divide

由于值太大或太小。我无法自己解决这个问题。有什么办法可以重新定义我的函数,让它在没有警告的情况下通过?

最佳答案

您可以使用 numpy.errstate这是一个内置的上下文管理器。这将允许您将错误处理设置在 with 语句的上下文中。

import numpy
# warning is not logged here. Perfect for clean unit test output
with numpy.errstate(divide='ignore'):
numpy.float64(1.0) / 0.0

我最近在为一些遗留 python 代码编写单元测试时不得不这样做。

关于 python : How to avoid numpy RuntimeWarning in function definition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519237/

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