問題描述
我被要求測試第 3 方提供的庫.眾所周知,該庫精確到 n 個有效數字.任何不太重要的錯誤都可以安全地忽略.我想寫一個函數來幫助我比較結果:
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:
def nearlyequal( a, b, sigfig=5 ):
此函數的目的是確定兩個浮點數(a 和 b)是否近似相等.如果 a==b(完全匹配)或者如果 a 和 b 在以十進制形式寫入時舍入到 sigfig 有效數字時具有相同的值,則該函數將返回 True.
The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.
任何人都可以提出一個好的實施方案嗎?我寫了一個迷你單元測試.除非你能在我的測試中看到一個錯誤,否則一個好的實現應該通過以下:
Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:
assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal( 1e4, 1e4 + 1, 5)
assert nearlyequal( 0.0, 1e-15, 5 )
assert not nearlyequal( 0.0, 1e-4, 6 )
補充說明:
- 值 a 和 b 可能是 int、float 或 numpy.float64 類型.值 a 和 b 將始終屬于同一類型.轉換不會給函數帶來額外的錯誤,這一點至關重要.
- 讓我們保留這個數字,因此轉換為字符串或使用非數學技巧的函數并不理想.該程序將由一位數學家審核,他希望能夠證明該函數完成了它應該做的事情.
- 速度...我要比較很多數字,所以越快越好.
- 我有 numpy、scipy 和標準庫.其他任何東西對我來說都很難得到,尤其是對于項目的這么小部分.
推薦答案
numpy.testing
中有一個函數assert_approx_equal
(來源這里)這可能是一個很好的起點.
There is a function assert_approx_equal
in numpy.testing
(source here) which may be a good starting point.
def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
"""
Raise an assertion if two items are not equal up to significant digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
這篇關于用于確定兩個數字在舍入到 n 個有效十進制數字時是否幾乎相等的函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!