本文介紹了測(cè)試浮點(diǎn)相等的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
在 python 中是否有測(cè)試浮點(diǎn)近似相等的函數(shù)?類似的,
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++ 測(cè)試庫(kù) gtest.h 定義 EXPECT_NEAR
的方式.
My use case is similar to how Google's C++ testing library, gtest.h, defines EXPECT_NEAR
.
這是一個(gè)例子:
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))
推薦答案
- 為了比較數(shù)字,有
math.isclose
. - 對(duì)于比較數(shù)字或數(shù)組,有
numpy.allclose
. - 對(duì)于測(cè)試數(shù)字或數(shù)組,有
numpy.testing.assert_allclose
這篇關(guān)于測(cè)試浮點(diǎn)相等的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!