Python 由其错误确定的值的有效数字
我需要一个函数,只返回与给定错误相关的值的有效部分。意思是这样的:Python 由其错误确定的值的有效数字,python,numpy,rounding,scientific-computing,Python,Numpy,Rounding,Scientific Computing,我需要一个函数,只返回与给定错误相关的值的有效部分。意思是这样的: def (value, error): """ This function takes a value and determines its significant accuracy by its error. It returns only the scientific important part of a value and drops the rest. """ magi
def (value, error):
""" This function takes a value and determines its significant
accuracy by its error.
It returns only the scientific important part of a value and drops the rest. """
magic magic magic....
return formated value as String.
到目前为止,我写了些什么来表达我的意思:
import numpy as np
def signigicant(value, error):
""" Returns a number in a scintific format. Meaning a value has an error
and that error determines how many digits of the
value are signifcant. e.g. value = 12.345MHz,
error = 0.1MHz => 12.3MHz because the error is at the first digit.
(in reality drop the MHz its just to show why.)"""
xx = "%E"%error # I assume this is most ineffective.
xx = xx.split("E")
xx = int(xx[1])
if error <= value: # this should be the normal case
yy = np.around(value, -xx)
if xx >= 0: # Error is 1 or bigger
return "%i"%yy
else: # Error is smaller than 1
string = "%."+str(-xx) +"f"
return string%yy
if error > value: # This should not be usual but it can happen.
return "%g"%value
例如:
>>> errors = [0.2,1.123,1.0, 123123.1233215,0.123123123768]
>>> values = [12.3453,123123321.4321432, 0.000321 ,321321.986123612361236,0.00001233214 ]
>>> map(round_on_error, values, errors)
[12.3, 123123321.0, 0.0, 300000.0, 0.0]
如果你想保持一个低于其误差的值
if (value < error)
return value
else
def round_on_error(value, error):
significant_digits = 10**math.floor(math.log(error, 10))
return value // significant_digits * significant_digits
if(值<错误)
返回值
其他的
def四舍五入打开错误(值,错误):
有效数字=10**数学下限(数学日志(错误,10))
返回值//有效数字*有效数字
AFAIK,对于科学计算来说,您不仅仅是放弃错误。如果某个值不精确,通常表示为12.345MHz±0.1MHz。
>>> errors = [0.2,1.123,1.0, 123123.1233215,0.123123123768]
>>> values = [12.3453,123123321.4321432, 0.000321 ,321321.986123612361236,0.00001233214 ]
>>> map(round_on_error, values, errors)
[12.3, 123123321.0, 0.0, 300000.0, 0.0]
if (value < error)
return value
else
def round_on_error(value, error):
significant_digits = 10**math.floor(math.log(error, 10))
return value // significant_digits * significant_digits