Comparing floats

Nobody nobody at nowhere.com
Mon Nov 29 00:20:13 CET 2010


On Sat, 27 Nov 2010 18:23:48 -0500, Terry Reedy wrote:

>> Therefore, to implement this multiplication operation I need to have a
>> way to verify that the float tuples C and D are "equal".
> 
> I might try the average relative difference:
> sum(abs((i-j)/(i+j)) for i,j in zip(C,D))/n # assuming lengths constant

The division is unstable if i and j are close to zero.

For scalars, I'd use:

	abs(i-j) <= epsilon * (1 + abs(i+j))

This amounts to a relative error check for large values and an absolute
error check for values close to zero.

For a vector, I'd check that the above holds for all pairs.




More information about the Python-list mailing list