Dalius
Dalius

Reputation: 736

Is it possible that a stored number in mysql double column can lose precision after several multiplications?

I have two tables. Let's say the first one is numbers with user_id + some number (double), can have multiple rows for each user_id. And then I have another users with user_id(PRIMARY) + product of all numbers for this user from the table numbers.

As records are inserted to or deleted from numbers, I need to recalculate users.product. Since there's only one record being inserted at a time, I can do it with this query:

UPDATE users SET product=product*{number} WHERE user_id={some_id}

but as records are removed in bulk, it would require some ugly code to do this, it's simpler to just recalculate the product. But, there's no such function as PRODUCT. I can use

exp(sum(log(coalesce(*number*,1)))

But I'm not sure if I won't end up with a wrong product of the numbers. The numbers will be in range from 1.00 to 9.99. How much of precision can be lost this way?

Upvotes: 2

Views: 124

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

The answer to the your question is "yes", if you are using floating point representations.

In general, if you are multiplying numbers in a small range and only have a handful of numbers, this isn't going to be a problem. If you are worried about it, then store the numbers in a fixed decimal representation.

Your solution of taking logs is fine. For most applications this is going to produce quite sufficient accuracy. But, if you working on sending an orbitor to Mars, small errors can accumulate, and you shouldn't depend on the database for high precision numerical accuracy.

Note that the ordering of calculations can also affect numeric precision.

Upvotes: 2

Related Questions