How to efficiently calculate $ax+b$ once I know $a$ and $b$?

121 Views Asked by At

What's the cheapest way to calculate $ax+b$ several times once I know the values for $a$ and $b$?

For instance, the cheapest way to calculate $a + b +x$ several times, once I know the values for $a$ and $b$, is to calculate $K = a+b$ once, and then calculate $K + x$ as much as I need.

Is there a way to calculate $ax+b$ that is cheaper than performing a multiplication followed by an addition, once $a$ and $b$ are fixed?

1

There are 1 best solutions below

0
On

Your alternatives are:

  1. Multiply by $a$ then add $b$.

  2. Add $b/a$ then multiply by $a$.

If $x$ is a similar size to $b/a$ then you should choose 2.

If $x$ is very different in size to $b/a$ then you should choose 1.

It's not so much about efficiency as the precision that you could lose. Adding two numbers of very different size can lead to a loss of precision.