I am trying to compare 2 values (float) using squish and it works fine sometimes, but fails few times. It is very inconsistent. Can someone help me how to use isclose
for comparing float values.
Following is my script:
Xposition_set = waitForObject("{id='textBoxGoto_Sample_X'}").text
Xposition_setValue = round(float(Xposition_set), 2)
Xposition_displayed = waitForObject("{id='dbxX' nativeObject.DataContext.Name='" + str(positionList[Index])+ "'}").text
Xposition_displayedValue = round(float(Xposition_displayed), 2)
test.compare(Xposition_setValue, Xposition_displayedValue, GetTestCaseNumber() + "X -Positions matches")
Check out the documentation for
math.isclose()
:Also note at the bottom:
So you should be sure you're running Python 3.5+ to use the function. But with that said, all you need to do is pass in your values. A standard example of floating point arithmetic error is usually adding
0.1 + 0.2
:So if we checked if that calculation is equal to
0.3
:With the new
math.isclose()
function, we can remedy that:Before Python 3.5, you can just do this manually. You just want to check if the absolute difference between the two numbers is very very small. The default tolerance for
math.isclose()
is1e-09
, so we can use that:In fact the difference between those two floats is far smaller than that even:
So you could use a stronger threshold, either for manual checking or if using
math.isclose()
and passing in a value forrel_tol
.