0

この質問に対する完全に異なる答えを見つけました。元の質問全体がもはや意味をなさない. ただし、答えの方法は役立つので、少し変更します...

、 、、 などの 3 つのdouble数値を、可能限り数値的に安定した方法で合計したいと考えています。カハン・サムを使うのがいいと思います。abc

しかし、私には奇妙な考えが浮かびました。

  1. まず、 、 、およびを合計しa、(の絶対値) 補償を覚えておいてください。bc
  2. a次に、 、c、 を合計します。b
  3. 2 番目の合計の補正 (の絶対値) が小さい場合は、代わりにこの合計を使用します。
  4. bacおよびその他の数字の順列についても同様に進めます。
  5. 関連する絶対補償が最小の合計を返します。

この方法で 3 つの数値のより「安定した」加算を取得できますか? それとも、合計の数字の順序は、合計の最後に残る補償に (使用可能な) 影響を与えませんか? (使用可能) とは、補償値自体が、使用できる情報を含むのに十分安定しているかどうかを尋ねることを意味します。

(ここでは関係ないと思いますが、Java プログラミング言語を使用しています。)

どうもありがとう、トーマス。

4

1 に答える 1

0

「3 を足す」(または「4 を足す」または「N を足す」) 数の問題を解決するための、より信頼できる方法を見つけたと思います。

まず、元の投稿からアイデアを実装しました。その結果、最初はうまくいくように見えたかなり大きなコードができました。ただし、次の場合は失敗しました: add Double.MAX_VALUE1、および-Double.MAX_VALUE。結果は でした0

@njuffa のコメントは、私がもう少し深く掘り下げるきっかけなりました。見事に解決しました。完全なコードを表示するために、 https: //www.python.org/getit/source/ から Python ソース (Python 3.5.1rc1 - 2015-11-23) をダウンロードしました。ここで、次のメソッドを見つけることができます (PYTHON SOFTWARE の下)。 FOUNDATION ライセンス バージョン 2):

static PyObject*
math_fsum(PyObject *self, PyObject *seq)
{
    PyObject *item, *iter, *sum = NULL;
    Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
    double x, y, t, ps[NUM_PARTIALS], *p = ps;
    double xsave, special_sum = 0.0, inf_sum = 0.0;
    volatile double hi, yr, lo;

    iter = PyObject_GetIter(seq);
    if (iter == NULL)
        return NULL;

    PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)

    for(;;) {           /* for x in iterable */
        assert(0 <= n && n <= m);
        assert((m == NUM_PARTIALS && p == ps) ||
               (m >  NUM_PARTIALS && p != NULL));

        item = PyIter_Next(iter);
        if (item == NULL) {
            if (PyErr_Occurred())
                goto _fsum_error;
            break;
        }
        x = PyFloat_AsDouble(item);
        Py_DECREF(item);
        if (PyErr_Occurred())
            goto _fsum_error;

        xsave = x;
        for (i = j = 0; j < n; j++) {       /* for y in partials */
            y = p[j];
            if (fabs(x) < fabs(y)) {
                t = x; x = y; y = t;
            }
            hi = x + y;
            yr = hi - x;
            lo = y - yr;
            if (lo != 0.0)
                p[i++] = lo;
            x = hi;
        }

        n = i;                              /* ps[i:] = [x] */
        if (x != 0.0) {
            if (! Py_IS_FINITE(x)) {
                /* a nonfinite x could arise either as
                   a result of intermediate overflow, or
                   as a result of a nan or inf in the
                   summands */
                if (Py_IS_FINITE(xsave)) {
                    PyErr_SetString(PyExc_OverflowError,
                          "intermediate overflow in fsum");
                    goto _fsum_error;
                }
                if (Py_IS_INFINITY(xsave))
                    inf_sum += xsave;
                special_sum += xsave;
                /* reset partials */
                n = 0;
            }
            else if (n >= m && _fsum_realloc(&p, n, ps, &m))
                goto _fsum_error;
            else
                p[n++] = x;
        }
    }

    if (special_sum != 0.0) {
        if (Py_IS_NAN(inf_sum))
            PyErr_SetString(PyExc_ValueError,
                            "-inf + inf in fsum");
        else
            sum = PyFloat_FromDouble(special_sum);
        goto _fsum_error;
    }

    hi = 0.0;
    if (n > 0) {
        hi = p[--n];
        /* sum_exact(ps, hi) from the top, stop when the sum becomes
           inexact. */
        while (n > 0) {
            x = hi;
            y = p[--n];
            assert(fabs(y) < fabs(x));
            hi = x + y;
            yr = hi - x;
            lo = y - yr;
            if (lo != 0.0)
                break;
        }
        /* Make half-even rounding work across multiple partials.
           Needed so that sum([1e-16, 1, 1e16]) will round-up the last
           digit to two instead of down to zero (the 1e-16 makes the 1
           slightly closer to two).  With a potential 1 ULP rounding
           error fixed-up, math.fsum() can guarantee commutativity. */
        if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
                      (lo > 0.0 && p[n-1] > 0.0))) {
            y = lo * 2.0;
            x = hi + y;
            yr = x - hi;
            if (y == yr)
                hi = x;
        }
    }
    sum = PyFloat_FromDouble(hi);

_fsum_error:
    PyFPE_END_PROTECT(hi)
    Py_DECREF(iter);
    if (p != ps)
        PyMem_Free(p);
    return sum;
}

この総和法は Kahan の方法とは異なり、可変数の補償変数を使用します。i番目の数値を追加するとき、最大でi追加の補正変数 (配列に格納されているp) が使用されます。これは、3 つの数値を追加したい場合、3 つの追加の変数が必要になる可能性があることを意味します。4 つの数値の場合、4 つの追加の変数が必要になる場合があります。使用される変数の数は、加数がロードされた後nn+1のみ増加する可能性があるため、n次のように上記のコードを Java に変換できます。

/**
 * Compute the exact sum of the values in the given array
 * {@code summands} while destroying the contents of said array.
 *
 * @param summands
 *          the summand array &ndash; will be summed up and destroyed
 * @return the accurate sum of the elements of {@code summands}
 */
private static final double __destructiveSum(final double[] summands) {
  int i, j, n;
  double x, y, t, xsave, hi, yr, lo;
  boolean ninf, pinf;

  n = 0;
  lo = 0d;
  ninf = pinf = false;

  for (double summand : summands) {

    xsave = summand;
    for (i = j = 0; j < n; j++) {
      y = summands[j];
      if (Math.abs(summand) < Math.abs(y)) {
        t = summand;
        summand = y;
        y = t;
      }
      hi = summand + y;
      yr = hi - summand;
      lo = y - yr;
      if (lo != 0.0) {
        summands[i++] = lo;
      }
      summand = hi;
    }

    n = i; /* ps[i:] = [summand] */
    if (summand != 0d) {
      if ((summand > Double.NEGATIVE_INFINITY)
          && (summand < Double.POSITIVE_INFINITY)) {
        summands[n++] = summand;// all finite, good, continue
      } else {
        if (xsave <= Double.NEGATIVE_INFINITY) {
          if (pinf) {
            return Double.NaN;
          }
          ninf = true;
        } else {
          if (xsave >= Double.POSITIVE_INFINITY) {
            if (ninf) {
              return Double.NaN;
            }
            pinf = true;
          } else {
            return Double.NaN;
          }
        }

        n = 0;
      }
    }
  }

  if (pinf) {
    return Double.POSITIVE_INFINITY;
  }
  if (ninf) {
    return Double.NEGATIVE_INFINITY;
  }

  hi = 0d;
  if (n > 0) {
    hi = summands[--n];
    /*
     * sum_exact(ps, hi) from the top, stop when the sum becomes inexact.
     */
    while (n > 0) {
      x = hi;
      y = summands[--n];
      hi = x + y;
      yr = hi - x;
      lo = y - yr;
      if (lo != 0d) {
        break;
      }
    }
    /*
     * Make half-even rounding work across multiple partials. Needed so
     * that sum([1e-16, 1, 1e16]) will round-up the last digit to two
     * instead of down to zero (the 1e-16 makes the 1 slightly closer to
     * two). With a potential 1 ULP rounding error fixed-up, math.fsum()
     * can guarantee commutativity.
     */
    if ((n > 0) && (((lo < 0d) && (summands[n - 1] < 0d)) || //
        ((lo > 0d) && (summands[n - 1] > 0d)))) {
      y = lo * 2d;
      x = hi + y;
      yr = x - hi;
      if (y == yr) {
        hi = x;
      }
    }
  }
  return hi;
}

この関数は、配列を取得summandsして要素を加算し、同時にそれを使用して補正変数を格納します。インデックスの配列要素が補償に使用されるsummandにインデックスをロードするため、これは機能します。i

追加する変数の数が少ない場合、配列は小さくなり、メソッドのスコープから逃れることができないため、JIT によって直接スタックに割り当てられる可能性が十分にあると思います。非常に高速にコーディングできます。

元のコードの作成者が無限大、オーバーフロー、および NaN を処理した理由を完全には理解していなかったことを認めます。ここで私のコードはオリジナルから逸脱しています。(私はそれを台無しにしなかったことを願っています。)

いずれにせよ、次のようにして、3、4、またはn double数を合計できるようになりました。

public static final double add3(final double x0, final double x1,
    final double x2) {
  return __destructiveSum(new double[] { x0, x1, x2 });
}

public static final double add4(final double x0, final double x1,
    final double x2, final double x3) {
  return __destructiveSum(new double[] { x0, x1, x2, x3 });
}

long3 つまたは 4 つの数値を合計して正確な結果を として取得したい場合、s は でのみs を表すことができるdoubleという事実に対処する必要があります。しかし、これはそれぞれを 2 つの部分に分割することで簡単に実行できます。doublelong-9007199254740992..9007199254740992Llong

 public static final long add3(final long x0, final long x1,
    final long x2) {
  double lx;
  return __destructiveSum(new long[] {new double[] { //
                lx = x0, //
                (x0 - ((long) lx)), //
                lx = x1, //
                (x1 - ((long) lx)), //
                lx = x2, //
                (x2 - ((long) lx)), //
            });
}

public static final long add4(final long x0, final long x1,
    final long x2, final long x3) {
  double lx;
  return __destructiveSum(new long[] {new double[] { //
                lx = x0, //
                (x0 - ((long) lx)), //
                lx = x1, //
                (x1 - ((long) lx)), //
                lx = x2, //
                (x2 - ((long) lx)), //
                lx = x3, //
                (x3 - ((long) lx)), //
            });
}

これくらいでいいと思います。少なくとも、 、 、および を追加Double.MAX_VALUE1て結果として-Double.MAX_VALUE取得できる1ようになりました。

于 2015-11-25T05:32:56.143 に答える