Efficient constant multiplication in C ++

I implement the Runge-Kutta procedure, which includes several time-critical multiplications with fixed complex fractions (which are not magic numbers, but inherent in the algorithm), and I want these multiplications to be executed as efficiently as possible, readable code.

For simplicity, let's assume that my code looks like this if I don't need to care about efficiency:

for (int i = 0; i < n; i++)
    a[i] += f(i) + b[i] * (2197/4104.);

Is it possible to assume that every reasonable compiler (with optimization) will effectively replace 2197/4104 with 0.535331 ...? If not, what are some good ways to do this? Could a definition const double, for example?

(Note that I'm not interested in other options for optimizing the above code - this is really just an example.)

+4
source share
2 answers

Using any recent compiler, evaluation will be performed at compile time.

However, if you cannot guarantee that the compiler will be, just take the calculation out of the loop (by creating const long double, if possible):

long double fraction = (2197/4104.);
for (int i = 0; i < n; i++)
  a[i] += f(i) + b[i] * fraction;

If summation accuracy is important and size f(i)or b[i]potentially large (I suppose it might be), you better not use it +=to summarize values, instead look at the Kahan summation algorithm to summarize with minimal loss of accuracy. Alternatively, try working with integral types when adding, and then do the division as the last step.

+4

, 100000 ( - , ) 100000. 2197/4104 53533, (28561/56430 = 0.50435 → 50435 ..) .

0

Source: https://habr.com/ru/post/1533731/


All Articles