Python:如何避免在函数定义中出现numpy RuntimeWarning? [英] Python : How to avoid numpy RuntimeWarning in function definition?

查看:1179
本文介绍了Python:如何避免在函数定义中出现numpy RuntimeWarning?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一个简单的函数来返回数学函数,该数学函数可用于将实验数据拟合到其中.函数看起来很像以下内容:

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.seterr控制numpy的功能:http://docs.scipy.org/doc/numpy/reference/generation/numpy.seterr.html

使用警告模块来控制警告的显示或不显示方式: http://docs.python.org/library /warnings.html

i designed a simple function to return a mathematical function which can be used to fit experimental data to it. The functions looks pretty much like the following:

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

Unfortunately I run into troubles with RunTimeWarnings as:

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

due to values that are too large or small. I am not able to figure this problem out on my own though. Is there any way to redefine my function so it will pass without warnings?

解决方案

Use numpy.seterr to control what numpy does in this circumstance: http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

Use the warnings module to control how warnings are or are not presented: http://docs.python.org/library/warnings.html

这篇关于Python:如何避免在函数定义中出现numpy RuntimeWarning?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆