Search code examples
floating-pointdarbitrary-precision

how to perform high precision calculations in D?


For some universitary work i have to approximate some numbers - like the Euler one with series. Therefore i have to add very small numbers, but i have problems with the precision. If the number ist very small it doesn't influence the result.

real s;  //sum of all previous terms
ulong k; //factorial

s += 1.0/ k;

after each step, k gets even smaller, but after the 10th round the result isn't changeing anymore and stuck at 2.71828


Solution

  • If you need a solution that will run using the native types you should be able to get reasonable results by trying to always add numbers of similar magnitude. One way to do this is to compute the first X terms of the series, and then repeatedly replace the two smallest numbers with there sum:

    auto data = real[N];
    foreach(i, ref v; data) {
      v = Fn(i);
    }
    
    while(data.length > 1) {
      data.sort(); // IIRC .sort is deprecated but I forget what replaced it.
      data[1] += data[0];
      data = data[1..$];
    }
    
    return data[0];
    

    (A min heap would make this a bit faster.)