本文介紹了測試浮點相等的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在 python 中是否有測試浮點近似相等的函數?類似的,
Is there a function to test floating point approximate equality in python? Something like,
def approx_equal(a, b, tol):
return abs(a - b) < tol
我的用例類似于 Google 的 C++ 測試庫 gtest.h 定義 EXPECT_NEAR
的方式.
My use case is similar to how Google's C++ testing library, gtest.h, defines EXPECT_NEAR
.
這是一個例子:
def bernoulli_fraction_to_angle(fraction):
return math.asin(sqrt(fraction))
def bernoulli_angle_to_fraction(angle):
return math.sin(angle) ** 2
def test_bernoulli_conversions():
assert(approx_equal(bernoulli_angle_to_fraction(pi / 4), 0.5, 1e-4))
assert(approx_equal(
bernoulli_fraction_to_angle(bernoulli_angle_to_fraction(0.1)),
0.1, 1e-4))
推薦答案
- 為了比較數字,有
math.isclose
. - 對于比較數字或數組,有
numpy.allclose
. - 對于測試數字或數組,有
numpy.testing.assert_allclose
這篇關于測試浮點相等的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!