jeudi 17 août 2017

Using assertAlmostEqual on big float numbers (divide and approximate to 1)

I'm trying to test if the putting some float to a DB, gets a fair approximation of it back. I generate the test numbers with hypothesis.

The real case is saving the number to a PostgreSQL DB and reading it back. All done by the Odoo 8 ORM (I can't use the monetary data type).

First I tried the obvious:

Line = self.env['test.monetary.line']
obj = Line.create({'value': value})
self.assertAlmostEqual(obj.value, value, places=7)

But this fails with big values because of loss of precision in the float point representation. When hypothesis generates the value 3.6893488147419103e+19, what I get back from the DB is just 3.68934881474191e+19. The difference between those numbers is 4096.

I tried then to do:

self.assertAlmostEqual(obj.value/value, 1, places=7)

(of course when values is not 0).

Question: Is a numerical/mathematically sound test?

PD. The test now fails for even bigger numbers like 1.79769313486e+308, because now obj.value is returned as inf. But I can deal with that because my application won't be dealing with such numbers.

Aucun commentaire:

Enregistrer un commentaire