Note that there are some explanatory texts on larger screens.

plurals
  1. POPrecise Multiplication
    primarykey
    data
    text
    <p>first post!</p> <p>I have a problem with a program that i'm writing for a numerical simulation and I have a problem with the multiplication. Basically, I am trying to calculate:</p> <pre><code>result1 = (a + b)*c </code></pre> <p>and this loops thousands of times. I need to expand this code to be</p> <pre><code>result2 = a*c + b*c </code></pre> <p>However, when I do that I start to get significant errors in my results. I used a high precision library, which did improve things, but the simulation ran horribly slow (the simulation took 50 times longer) and it really isn't a practical solution. From this I realised that it isn't really the precision of the variables a, b, &amp; c that is hurting me, but something in the way the multiplication is done. </p> <p>My question is: how can I multiply out these brackets in way so that result1 = result2?</p> <p>Thanks.</p> <p>SOLVED!!!!!!!!!</p> <p>It was a problem with the addition. So i reordered the terms and applied Kahan addition by writing the following piece of code:</p> <pre><code>double Modelsimple::sum(double a, double b, double c, double d) { //reorder the variables in order from smallest to greatest double tempone = (a&lt;b?a:b); double temptwo = (c&lt;d?c:d); double tempthree = (a&gt;b?a:b); double tempfour = (c&gt;d?c:d); double one = (tempone&lt;temptwo?tempone:temptwo); double four = (tempthree&gt;tempfour?tempthree:tempfour); double tempfive = (tempone&gt;temptwo?tempone:temptwo); double tempsix = (tempthree&lt;tempfour?tempthree:tempfour); double two = (tempfive&lt;tempsix?tempfive:tempsix); double three = (tempfive&gt;tempsix?tempfive:tempsix); //kahan addition double total = one; double tempsum = one + two; double error = (tempsum - one) - two; total = tempsum; // first iteration complete double tempadd = three - error; tempsum = total + tempadd; error = (tempsum - total) - tempadd; total = tempsum; //second iteration complete tempadd = four - error; total += tempadd; return total; } </code></pre> <p>This gives me results that are as close to the precise answer as makes no difference. However, in a fictitious simulation of a mine collapse, the code with the Kahan addition takes 2 minutes whereas the high precision library takes over a day to finish!!</p> <p>Thanks to all the help here. This problem was really a pain in the a$$.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload