I have vector computation expressions like this
-((v2*w1 - v1*w2 - w1*x1 w2*x1 v1*y1 - v2*y1)/
(w1*x1 - w2*x1 - w1*x2 w2*x2 - v1*y1 v2*y1 v1*y2 - v2*y2))
They are for C-like languages, like C/C , Java, C#.
Can I automatically optimize them for precision / multiplications count?
I need to optimize expression itself. For example, numerator can be simplified to something like this
-((w1 - w2)*x1) v2*(w1 - y1) - v1*(w2 - y1)
(I could mistake)
CodePudding user response:
No, you can't do that without numerical analysis.
Take just a simple subterm, w1*x1 - w2*x1. This can lose precision due to under- or overflow. Replacing it with (w1-w2)*x1 still can lose precision due to under- or overflow, but the values for which that happens are different.
Even for this simple case, you need to take into account whether w1, w2 or their difference is denormal, whether x1 is bigger or smaller than 1.0, and (since this appears in the divisor) whether any of the terms could be infinity.
CodePudding user response:
Generally speaking, there is no magic wand when it comes to cancellation errors. You should be very careful around subtractions and especially when your arguments vary greatly in scale. If most of your arguments are very large or very small except one - you should do this multiplication/division as the last operation. If all of your arguments are of a comparable scale, there is nothing to worry about.
Your simplification of the numerator will be of any advantage only if it avoids subtractions of arguments of a very different scale - this is the real problem.
