public double execute(double in) throws DMLRuntimeException {
    switch (bFunc) {
      case SIN:
        return FASTMATH ? FastMath.sin(in) : Math.sin(in);
      case COS:
        return FASTMATH ? FastMath.cos(in) : Math.cos(in);
      case TAN:
        return FASTMATH ? FastMath.tan(in) : Math.tan(in);
      case ASIN:
        return FASTMATH ? FastMath.asin(in) : Math.asin(in);
      case ACOS:
        return FASTMATH ? FastMath.acos(in) : Math.acos(in);
      case ATAN:
        return Math.atan(in); // faster in Math
      case CEIL:
        return FASTMATH ? FastMath.ceil(in) : Math.ceil(in);
      case FLOOR:
        return FASTMATH ? FastMath.floor(in) : Math.floor(in);
      case LOG:
        return FASTMATH ? FastMath.log(in) : Math.log(in);
      case LOG_NZ:
        return (in == 0) ? 0 : FASTMATH ? FastMath.log(in) : Math.log(in);
      case ABS:
        return Math.abs(in); // no need for FastMath	
      case SIGN:
        return FASTMATH ? FastMath.signum(in) : Math.signum(in);
      case SQRT:
        return Math.sqrt(in); // faster in Math
      case EXP:
        return FASTMATH ? FastMath.exp(in) : Math.exp(in);
      case ROUND:
        return Math.round(in); // no need for FastMath

      case PLOGP:
        if (in == 0.0) return 0.0;
        else if (in < 0) return Double.NaN;
        else return (in * (FASTMATH ? FastMath.log(in) : Math.log(in)));

      case SPROP:
        // sample proportion: P*(1-P)
        return in * (1 - in);

      case SIGMOID:
        // sigmoid: 1/(1+exp(-x))
        return FASTMATH ? 1 / (1 + FastMath.exp(-in)) : 1 / (1 + Math.exp(-in));

      case SELP:
        // select positive: x*(x>0)
        return (in > 0) ? in : 0;

      default:
        throw new DMLRuntimeException("Builtin.execute(): Unknown operation: " + bFunc);
    }
  }
 /* (non-Javadoc)
  * @see net.finmath.stochastic.RandomVariableInterface#exp()
  */
 public RandomVariable exp() {
   if (isDeterministic()) {
     double newValueIfNonStochastic = FastMath.exp(valueIfNonStochastic);
     return new RandomVariable(time, newValueIfNonStochastic);
   } else {
     double[] newRealizations = new double[realizations.length];
     for (int i = 0; i < newRealizations.length; i++)
       newRealizations[i] = FastMath.exp(realizations[i]);
     return new RandomVariable(time, newRealizations);
   }
 }
 public double value(double[] x) {
   double f = 0;
   double res2 = 0;
   double fac = 0;
   for (int i = 0; i < x.length; ++i) {
     fac = FastMath.pow(axisratio, (i - 1.) / (x.length - 1.));
     f += fac * fac * x[i] * x[i];
     res2 += FastMath.cos(2. * FastMath.PI * fac * x[i]);
   }
   f =
       (20.
           - 20. * FastMath.exp(-0.2 * FastMath.sqrt(f / x.length))
           + FastMath.exp(1.)
           - FastMath.exp(res2 / x.length));
   return f;
 }
Exemple #4
0
 @Override
 public IComplexNumber exp() {
   IComplexNumber result = dup();
   double realExp = FastMath.exp(realComponent());
   return result.set(
       realExp * FastMath.cos(imaginaryComponent()), realExp * FastMath.sin(imaginaryComponent()));
 }
Exemple #5
0
    /**
     * Computes the value of the gradient at {@code x}. The components of the gradient vector are
     * the partial derivatives of the function with respect to each of the <em>parameters</em>
     * (lower asymptote and higher asymptote).
     *
     * @param x Value at which the gradient must be computed.
     * @param param Values for lower asymptote and higher asymptote.
     * @return the gradient vector at {@code x}.
     * @throws NullArgumentException if {@code param} is {@code null}.
     * @throws DimensionMismatchException if the size of {@code param} is not 2.
     */
    public double[] gradient(double x, double... param) {
      validateParameters(param);

      final double invExp1 = 1 / (1 + FastMath.exp(-x));

      return new double[] {1 - invExp1, invExp1};
    }
Exemple #6
0
 public double[] initExpTable() {
   double[] expTable = new double[1000];
   for (int i = 0; i < expTable.length; i++) {
     double tmp = FastMath.exp((i / (double) expTable.length * 2 - 1) * MAX_EXP);
     expTable[i] = tmp / (tmp + 1.0);
   }
   return expTable;
 }
Exemple #7
0
  /**
   * Compute the <a href="http://mathworld.wolfram.com/ExponentialFunction.html" TARGET="_top">
   * exponential function</a> of this complex number. Implements the formula:
   *
   * <pre>
   *  <code>
   *   exp(a + bi) = exp(a)cos(b) + exp(a)sin(b)i
   *  </code>
   * </pre>
   *
   * where the (real) functions on the right-hand side are {@link java.lang.Math#exp}, {@link
   * java.lang.Math#cos}, and {@link java.lang.Math#sin}. <br>
   * Returns {@link Complex#NaN} if either real or imaginary part of the input argument is {@code
   * NaN}. <br>
   * Infinite values in real or imaginary parts of the input may result in infinite or NaN values
   * returned in parts of the result.
   *
   * <pre>
   *  Examples:
   *  <code>
   *   exp(1 &plusmn; INFINITY i) = NaN + NaN i
   *   exp(INFINITY + i) = INFINITY + INFINITY i
   *   exp(-INFINITY + i) = 0 + 0i
   *   exp(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
   *  </code>
   * </pre>
   *
   * @return <code><i>e</i><sup>this</sup></code>.
   * @since 1.2
   */
  public Complex exp() {
    if (isNaN) {
      return NaN;
    }

    double expReal = FastMath.exp(real);
    return createComplex(expReal * FastMath.cos(imaginary), expReal * FastMath.sin(imaginary));
  }
Exemple #8
0
 private static IComplexNumber sigmoidDeriv(IComplexNumber number) {
   double arg = number.complexArgument().doubleValue();
   double sigArg = 1 / 1 + (FastMath.exp(-arg)) - 1 + .5f;
   double ret = Math.exp(sigArg);
   IComplexDouble sigmoid = Nd4j.createDouble(ret, 0);
   IComplexNumber oneMinus = Nd4j.createComplexNumber(1, 1).subi(sigmoid);
   return sigmoid.mul(oneMinus);
 }
Exemple #9
0
 private static double sigmoidDeriv(double input) {
   double sigmoid = 1 / (1 + FastMath.exp(-input));
   double out = sigmoid * (1.0 - sigmoid);
   if (Nd4j.ENFORCE_NUMERICAL_STABILITY && (Double.isNaN(out) || Double.isInfinite(out))) {
     out = Nd4j.EPS_THRESHOLD;
   }
   return out;
 }
 /**
  * {@inheritDoc}
  *
  * <p>The implementation of this method is based on:
  *
  * <ul>
  *   <li><a href="http://mathworld.wolfram.com/ExponentialDistribution.html">Exponential
  *       Distribution</a>, equation (1).
  * </ul>
  */
 public double cumulativeProbability(double x) {
   double ret;
   if (x <= 0.0) {
     ret = 0.0;
   } else {
     ret = 1.0 - FastMath.exp(-x / mean);
   }
   return ret;
 }
  /**
   * Return the discount factor within a given model context for a given maturity.
   *
   * @param model The model used as a context (not required for this class).
   * @param maturity The maturity in terms of ACT/365 daycount form this curve reference date. Note
   *     that this parameter might get rescaled to a different time parameter.
   * @see
   *     net.finmath.marketdata.model.curves.DiscountCurveInterface#getDiscountFactor(net.finmath.marketdata.model.AnalyticModelInterface,
   *     double)
   */
  @Override
  public double getDiscountFactor(AnalyticModelInterface model, double maturity) {
    // Change time scale
    maturity *= timeScaling;

    double beta1 = parameter[0];
    double beta2 = parameter[1];
    double beta3 = parameter[2];
    double beta4 = parameter[3];
    double tau1 = parameter[4];
    double tau2 = parameter[5];

    double x1 = tau1 > 0 ? FastMath.exp(-maturity / tau1) : 0.0;
    double x2 = tau2 > 0 ? FastMath.exp(-maturity / tau2) : 0.0;

    double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0 - x1) / maturity * tau1 : 1.0) : 0.0;
    double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0 - x2) / maturity * tau2 : 1.0) : 0.0;

    double zeroRate = beta1 + beta2 * y1 + beta3 * (y1 - x1) + beta4 * (y2 - x2);

    return Math.exp(-zeroRate * maturity);
  }
Exemple #12
0
 /**
  * Returns te probability of each of the key items in the pattern. It leverages Poisson
  * distribution. See the paper for its description
  *
  * @param distribution
  * @param pattern
  * @return
  */
 private double getProb(Distribution distribution, Map<Integer, Integer> pattern) {
   return pattern
       .entrySet()
       .stream()
       .mapToDouble(
           e -> {
             double l = distribution.getFreq(e.getKey()) / capwidth;
             return l == 0
                 ? 0
                 : (new PoissonDistribution(l).probability(e.getValue()) / FastMath.exp(-l));
           })
       .reduce((a, b) -> (a * b))
       .getAsDouble();
 }
Exemple #13
0
  /**
   * Returns the regularized beta function I(x, a, b).
   *
   * <p>The implementation of this method is based on:
   *
   * <ul>
   *   <li><a href="http://mathworld.wolfram.com/RegularizedBetaFunction.html">Regularized Beta
   *       Function</a>.
   *   <li><a href="http://functions.wolfram.com/06.21.10.0001.01">Regularized Beta Function</a>.
   * </ul>
   *
   * @param x the value.
   * @param a Parameter {@code a}.
   * @param b Parameter {@code b}.
   * @param epsilon When the absolute value of the nth item in the series is less than epsilon the
   *     approximation ceases to calculate further elements in the series.
   * @param maxIterations Maximum number of "iterations" to complete.
   * @return the regularized beta function I(x, a, b)
   * @throws org.apache.commons.math3.exception.MaxCountExceededException if the algorithm fails to
   *     converge.
   */
  public static double regularizedBeta(
      double x, final double a, final double b, double epsilon, int maxIterations) {
    double ret;

    if (Double.isNaN(x)
        || Double.isNaN(a)
        || Double.isNaN(b)
        || x < 0
        || x > 1
        || a <= 0.0
        || b <= 0.0) {
      ret = Double.NaN;
    } else if (x > (a + 1.0) / (a + b + 2.0)) {
      ret = 1.0 - regularizedBeta(1.0 - x, b, a, epsilon, maxIterations);
    } else {
      ContinuedFraction fraction =
          new ContinuedFraction() {

            @Override
            protected double getB(int n, double x) {
              double ret;
              double m;
              if (n % 2 == 0) { // even
                m = n / 2.0;
                ret = (m * (b - m) * x) / ((a + (2 * m) - 1) * (a + (2 * m)));
              } else {
                m = (n - 1.0) / 2.0;
                ret = -((a + m) * (a + b + m) * x) / ((a + (2 * m)) * (a + (2 * m) + 1.0));
              }
              return ret;
            }

            @Override
            protected double getA(int n, double x) {
              return 1.0;
            }
          };
      ret =
          FastMath.exp(
                  (a * FastMath.log(x))
                      + (b * FastMath.log(1.0 - x))
                      - FastMath.log(a)
                      - logBeta(a, b))
              * 1.0
              / fraction.evaluate(x, epsilon, maxIterations);
    }

    return ret;
  }
  /** {@inheritDoc} */
  public double probability(int x) {
    double ret;

    int[] domain = getDomain(populationSize, numberOfSuccesses, sampleSize);
    if (x < domain[0] || x > domain[1]) {
      ret = 0.0;
    } else {
      double p = (double) sampleSize / (double) populationSize;
      double q = (double) (populationSize - sampleSize) / (double) populationSize;
      double p1 = SaddlePointExpansion.logBinomialProbability(x, numberOfSuccesses, p, q);
      double p2 =
          SaddlePointExpansion.logBinomialProbability(
              sampleSize - x, populationSize - numberOfSuccesses, p, q);
      double p3 = SaddlePointExpansion.logBinomialProbability(sampleSize, populationSize, p, q);
      ret = FastMath.exp(p1 + p2 - p3);
    }

    return ret;
  }
 @GenerateMicroBenchmark
 public void commonsmath(BlackHole hole) {
   for (int i = 0; i < data.length - 1; i++) hole.consume(FastMath.exp(data[i]));
 }
Exemple #16
0
 @Override
 public float op(float origin) {
   return (float) FastMath.exp(origin);
 }
Exemple #17
0
 @Override
 public double op(double origin) {
   return FastMath.exp(origin);
 }
 /** {@inheritDoc} */
 public double density(double x) {
   final double logDensity = logDensity(x);
   return logDensity == Double.NEGATIVE_INFINITY ? 0 : FastMath.exp(logDensity);
 }
  @Test
  public void testMissedEndEvent()
      throws DimensionMismatchException, NumberIsTooSmallException, MaxCountExceededException,
          NoBracketingException {
    final double t0 = 1878250320.0000029;
    final double tEvent = 1878250379.9999986;
    final double[] k = {1.0e-4, 1.0e-5, 1.0e-6};
    FirstOrderDifferentialEquations ode =
        new FirstOrderDifferentialEquations() {

          public int getDimension() {
            return k.length;
          }

          public void computeDerivatives(double t, double[] y, double[] yDot) {
            for (int i = 0; i < y.length; ++i) {
              yDot[i] = k[i] * y[i];
            }
          }
        };

    DormandPrince853Integrator integrator =
        new DormandPrince853Integrator(
            0.0, 100.0,
            1.0e-10, 1.0e-10);

    double[] y0 = new double[k.length];
    for (int i = 0; i < y0.length; ++i) {
      y0[i] = i + 1;
    }
    double[] y = new double[k.length];

    integrator.setInitialStepSize(60.0);
    double finalT = integrator.integrate(ode, t0, y0, tEvent, y);
    Assert.assertEquals(tEvent, finalT, 5.0e-6);
    for (int i = 0; i < y.length; ++i) {
      Assert.assertEquals(y0[i] * FastMath.exp(k[i] * (finalT - t0)), y[i], 1.0e-9);
    }

    integrator.setInitialStepSize(60.0);
    integrator.addEventHandler(
        new EventHandler() {

          public void init(double t0, double[] y0, double t) {}

          public void resetState(double t, double[] y) {}

          public double g(double t, double[] y) {
            return t - tEvent;
          }

          public Action eventOccurred(double t, double[] y, boolean increasing) {
            Assert.assertEquals(tEvent, t, 5.0e-6);
            return Action.CONTINUE;
          }
        },
        Double.POSITIVE_INFINITY,
        1.0e-20,
        100);
    finalT = integrator.integrate(ode, t0, y0, tEvent + 120, y);
    Assert.assertEquals(tEvent + 120, finalT, 5.0e-6);
    for (int i = 0; i < y.length; ++i) {
      Assert.assertEquals(y0[i] * FastMath.exp(k[i] * (finalT - t0)), y[i], 1.0e-9);
    }
  }
Exemple #20
0
  /**
   * The main fitting method of Random Walk smoother.
   *
   * @param additiveFit - object of AdditiveFit class
   * @return residuals
   */
  public ArrayRealVector solve(AdditiveFit additiveFit) {

    ArrayRealVector y = additiveFit.getZ();
    ArrayRealVector w = additiveFit.getW();
    int whichDistParameter = additiveFit.getWhichDistParameter();

    // if (any(is.na(y)))
    for (int i = 0; i < y.getDimension(); i++) {
      if (Double.isNaN(y.getEntry(i))) {

        // weights[is.na(y)] <- 0
        w.setEntry(i, 0.0);

        // y[is.na(y)] <- 0
        y.setEntry(i, 0.0);
      }
    }

    // N <- length(y)
    n = y.getDimension();
    // -------------------------------------------------------  BECOMES VERY SLOW HERE
    // W <- diag.spam(x=weights)  # weights
    wM = (BlockRealMatrix) MatrixUtils.createRealDiagonalMatrix(w.getDataRef());

    // E <- diag.spam(N)
    eM = MatrixFunctions.buildIdentityMatrix(n);

    // D <- diff(E, diff = order) # order
    dM = MatrixFunctions.diff(eM, Controls.RW_ORDER);
    // -------------------------------------------------------  FREEZES HERE
    // G <- t(D)%*%D
    gM = dM.transpose().multiply(dM);

    // logsig2e <- log(sig2e) # getting logs
    double logsig2e = FastMath.log(sigmasHash.get(whichDistParameter)[0]);

    // logsig2b <- log(sig2b)
    double logsig2b = FastMath.log(sigmasHash.get(whichDistParameter)[1]);

    // fv <- solve(exp(-logsig2e)*W + exp(-logsig2b)*G,
    // (exp(-logsig2e)*W)%*% as.vector(y))
    solver =
        new QRDecomposition(
                wM.scalarMultiply(FastMath.exp(-logsig2e))
                    .add(gM.scalarMultiply(FastMath.exp(-logsig2b))))
            .getSolver();

    fv = (ArrayRealVector) solver.solve(wM.scalarMultiply(FastMath.exp(-logsig2e)).operate(y));

    // if (sig2e.fix==FALSE && sig2b.fix==FALSE) # both estimated{
    if (Controls.SIG2E_FIX) {
      if (Controls.SIG2B_FIX) {

        // out <- list()
        // par <- c(logsig2e, logsig2b)
        // out$par <- par
        // value.of.Q <- -Qf(par)
        valueOfQ = -qF(new double[] {logsig2e, logsig2b}, y, w);

        // se <- NULL
        se = null;

      } else {

        // par <- log(sum((D%*%fv)^2)/N)
        tempV = (ArrayRealVector) dM.operate(fv);
        logsig2b = FastMath.log(MatrixFunctions.sumV(tempV.ebeMultiply(tempV)) / n);

        // Qf1 <- function(par)  Qf(c(logsig2e, par))
        // out<-nlminb(start = par,objective = Qf1,
        // lower = c(-20), upper = c(20))

        nonLinObj1.setResponse(y);
        nonLinObj1.setWeights(w);
        nonLinObj1.setLogsig2e(logsig2e);

        maxiter = new MaxIter(Controls.BOBYQA_MAX_ITER);
        maxeval = new MaxEval(Controls.BOBYQA_MAX_EVAL);
        initguess = new InitialGuess(new double[] {logsig2b, logsig2b});
        bounds =
            new SimpleBounds(
                new double[] {-Double.MAX_VALUE, -Double.MAX_VALUE},
                new double[] {Double.MAX_VALUE, Double.MAX_VALUE});
        obj = new ObjectiveFunction(nonLinObj1);
        PointValuePair values =
            optimizer.optimize(maxiter, maxeval, obj, initguess, bounds, GoalType.MINIMIZE);

        logsig2b = values.getPoint()[0];

        if (logsig2b > 20.0) {
          logsig2b = 20.0;
          valueOfQ = -qF(new double[] {logsig2e, logsig2b}, y, w);
        } else if (logsig2b < -20.0) {
          logsig2b = -20.0;
          valueOfQ = -qF(new double[] {logsig2e, logsig2b}, y, w);
        } else {
          valueOfQ = -values.getValue();
        }

        // out$hessian <- optimHess(out$par, Qf1)
        // value.of.Q <- -out$objective
        // shes <- 1/out$hessian
        // se1 <- ifelse(shes>0, sqrt(shes), NA)
        // par <- c(logsig2e, out$par)
        // names(par) <- c("logsig2e", "logsig2b")
        /// out$par <- par
        // se <- c(NA, se1)
        // System.out.println(logsig2e+"   "+logsig2b +"   "+qF(new double[]{logsig2e, logsig2b}, y,
        // w));
      }
    } else {
      if (Controls.SIG2B_FIX) {

        // par <- log(sum(weights*(y-fv)^2)/N)
        tempV = y.subtract(fv);
        logsig2e = FastMath.log(MatrixFunctions.sumV(tempV.ebeMultiply(tempV).ebeMultiply(w)) / n);

        // Qf2 <- function(par)  Qf(c(par, logsig2b))
        // out <- nlminb(start = par, objective = Qf2,
        // lower = c(-20),  upper = c(20))
        nonLinObj2.setResponse(y);
        nonLinObj2.setWeights(w);
        nonLinObj2.setLogsig2b(logsig2b);

        maxiter = new MaxIter(Controls.BOBYQA_MAX_ITER);
        maxeval = new MaxEval(Controls.BOBYQA_MAX_EVAL);
        initguess = new InitialGuess(new double[] {logsig2e, logsig2e});
        bounds =
            new SimpleBounds(
                new double[] {-Double.MAX_VALUE, -Double.MAX_VALUE},
                new double[] {Double.MAX_VALUE, Double.MAX_VALUE});
        obj = new ObjectiveFunction(nonLinObj2);
        PointValuePair values =
            optimizer.optimize(maxiter, maxeval, obj, initguess, bounds, GoalType.MINIMIZE);

        logsig2e = values.getPoint()[0];

        // out$hessian <- optimHess(out$par, Qf2)
        // value.of.Q <- -out$objective
        if (logsig2e > 20.0) {
          logsig2e = 20.0;
          valueOfQ = -qF(new double[] {logsig2e, logsig2b}, y, w);
        } else if (logsig2e < -20.0) {
          logsig2e = -20.0;
          valueOfQ = -qF(new double[] {logsig2e, logsig2b}, y, w);
        } else {
          valueOfQ = -values.getValue();
        }

        // shes <- 1/out$hessian
        // se1 <- ifelse(shes>0, sqrt(shes), NA)
        // par <- c( out$par, logsig2b)
        // names(par) <- c("logsig2e", "logsig2b")
        // out$par <- par
        // se <- c(se1, NA)
        // System.out.println(logsig2e+"   "+logsig2b +"   "+qF(new double[]{logsig2e, logsig2b}, y,
        // w));

      } else {

        // par <- c(logsig2e <- log(sum(weights*(y-fv)^2)/N),
        // logsig2b <-log(sum((D%*%fv)^2)/N))
        tempV = y.subtract(fv);
        logsig2e = FastMath.log(MatrixFunctions.sumV(w.ebeMultiply(tempV).ebeMultiply(tempV)) / n);

        tempV = (ArrayRealVector) dM.operate(fv);
        logsig2b = FastMath.log(MatrixFunctions.sumV(tempV.ebeMultiply(tempV)) / n);

        nonLinObj.setResponse(y);
        nonLinObj.setWeights(w);

        // out <- nlminb(start = par, objective = Qf,
        // lower = c(-20, -20),  upper = c(20, 20))
        maxiter = new MaxIter(Controls.BOBYQA_MAX_ITER);
        maxeval = new MaxEval(Controls.BOBYQA_MAX_EVAL);
        initguess = new InitialGuess(new double[] {logsig2e, logsig2b});
        bounds = new SimpleBounds(new double[] {-20.0, -20.0}, new double[] {20.0, 20.0});
        obj = new ObjectiveFunction(nonLinObj);
        PointValuePair values =
            optimizer.optimize(maxiter, maxeval, obj, initguess, bounds, GoalType.MINIMIZE);

        logsig2e = values.getPoint()[0];
        logsig2b = values.getPoint()[1];

        // System.out.println(logsig2e+"   "+logsig2b +"   "+values.getValue());

        // out$hessian <- optimHess(out$par, Qf) !!! Missing in Java
        // value.of.Q <- -out$objective
        valueOfQ = -values.getValue();

        // shes <- try(solve(out$hessian))
        // se <- if (any(class(shes)%in%"try-error"))
        // rep(NA_real_,2) else sqrt(diag(shes))
      }
    }

    // fv <- solve(exp(-out$par[1])*W + exp(-out$par[2])*G,
    // (exp(-out$par[1])*W)%*% as.vector(y))
    solver =
        new QRDecomposition(
                wM.scalarMultiply(FastMath.exp(-logsig2e))
                    .add(gM.scalarMultiply(FastMath.exp(-logsig2b))))
            .getSolver();

    fv = (ArrayRealVector) solver.solve(wM.scalarMultiply(FastMath.exp(-logsig2e)).operate(y));

    sigmasHash.put(
        whichDistParameter, new Double[] {FastMath.exp(logsig2e), FastMath.exp(logsig2b)});

    // b <- diff(fv, differences=order)
    b = MatrixFunctions.diffV(fv, Controls.RW_ORDER);

    // tr1 <- order + sum(b^2)/(exp(out$par[2])) # this always right
    // attributes(tr1) <- NULL
    double tr1 =
        Controls.RW_ORDER + MatrixFunctions.sumV(b.ebeMultiply(b)) / (FastMath.exp(logsig2b));

    tempV = null;
    return y.subtract(fv);
  }
Exemple #21
0
  // Qf <- function(par)
  private double qF(double[] par, ArrayRealVector y, ArrayRealVector w) {

    // fv <- solve((exp(-par[1])*W) + (exp(-par[2])*G),
    // (exp(-par[1])*W)%*%as.vector(y))
    solver =
        new QRDecomposition(
                wM.scalarMultiply(FastMath.exp(-par[0]))
                    .add(gM.scalarMultiply(FastMath.exp(-par[1]))))
            .getSolver();

    fv = (ArrayRealVector) solver.solve(wM.scalarMultiply(FastMath.exp(-par[0])).operate(y));

    // b <- diff(fv, differences=order)
    b = MatrixFunctions.diffV(fv, Controls.RW_ORDER);

    // DT <-  determinant((exp(-par[1])*W) + (exp(-par[2])*G))$modulus
    double dt =
        new LUD(
                wM.scalarMultiply(FastMath.exp(-par[0]))
                    .add(gM.scalarMultiply(FastMath.exp(-par[1]))))
            .getDeterminant();

    // f <- -(N/2)*log(2*pi*exp(par[1])) +           # 1
    tempV = y.subtract(fv);
    double f =
        -(n / 2) * FastMath.log(2 * FastMath.PI * FastMath.exp(par[0]))

            //               .5*sum(log(weights))-                   # 2
            + 0.5 * MatrixFunctions.sumV(MatrixFunctions.logVec(w))

            //               sum(weights*(y-fv)^2)/(2*exp(par[1])) + # 3
            - MatrixFunctions.sumV(w.ebeMultiply(tempV).ebeMultiply(tempV))
                / (2 * FastMath.exp(par[0]))

            //               (N/2)*log(2*pi) -                       # 4
            + (n * FastMath.log(2 * FastMath.PI)) / 2

            //               ((N-order)/2)*log(2*pi*exp(par[2]))-    # 5
            - ((n - Controls.RW_ORDER) * FastMath.log(2 * FastMath.PI * FastMath.exp(par[1]))) / 2

            //              sum(b^2)/(2*exp(par[2])) -              # 6
            - MatrixFunctions.sumV(b.ebeMultiply(b)) / (2 * FastMath.exp(par[1]))

            //               .5*DT								   # 7
            - 0.5 * dt;

    // attributes(f) <- NULL
    // Pen <- if (penalty==TRUE) delta[1]*(par[1]-shift[1])^2
    // + delta[2]*(par[2]-shift[2])^2 else 0 -f+Pen
    double pen = 0;
    if (Controls.PENALTY) {
      pen =
          delta.getEntry(0) * (par[0] - Controls.RW_SHIFT[0]) * (par[0] - Controls.RW_SHIFT[0])
              + delta.getEntry(1)
                  * (par[1] - Controls.RW_SHIFT[1])
                  * (par[1] - Controls.RW_SHIFT[1]);
    }

    // -f+Pen  # no penalty  yet
    return (-f + pen);
  }
 /**
  * Returns the exp of a complex number: Let r be the real component and i be the imaginary Let ret
  * be the complex number returned ret -> exp(r) * cos(i), exp(r) * sin(i) where the first number
  * is the real component and the second number is the imaginary component
  *
  * @param d the number to getFromOrigin the exp of
  * @return the exponential of this complex number
  */
 public static ComplexDouble exp(ComplexDouble d) {
   return new ComplexDouble(
       FastMath.exp(d.real()) * FastMath.cos(d.imag()),
       FastMath.exp(d.real()) * FastMath.sin(d.imag()));
 }
 /**
  * Returns the exp of a complex number: Let r be the real component and i be the imaginary Let ret
  * be the complex number returned ret -> exp(r) * cos(i), exp(r) * sin(i) where the first number
  * is the real component and the second number is the imaginary component
  *
  * @param d the number to getFromOrigin the exp of
  * @return the exponential of this complex number
  */
 public static ComplexFloat exp(ComplexFloat d) {
   return new ComplexFloat(
       (float) FastMath.exp(d.real()) * (float) FastMath.cos(d.imag()),
       (float) FastMath.exp(d.real()) * (float) FastMath.sin(d.imag()));
 }
 /**
  * For this distribution, {@code X}, defined by the given hypergeometric distribution parameters,
  * this method returns {@code P(X = x)}.
  *
  * @param x Value at which the PMF is evaluated.
  * @param n the population size.
  * @param m number of successes in the population.
  * @param k the sample size.
  * @return PMF for the distribution.
  */
 private double probability(int n, int m, int k, int x) {
   return FastMath.exp(
       ArithmeticUtils.binomialCoefficientLog(m, x)
           + ArithmeticUtils.binomialCoefficientLog(n - m, k - x)
           - ArithmeticUtils.binomialCoefficientLog(n, k));
 }
 /** {@inheritDoc} */
 public double density(double x) {
   final double x0 = x - mean;
   final double x1 = x0 / standardDeviation;
   return FastMath.exp(-0.5 * x1 * x1) / (standardDeviation * SQRT2PI);
 }
Exemple #26
0
 /**
  * @param x Value at which to compute the sigmoid.
  * @param lo Lower asymptote.
  * @param hi Higher asymptote.
  * @return the value of the sigmoid function at {@code x}.
  */
 private static double value(double x, double lo, double hi) {
   return lo + (hi - lo) / (1 + FastMath.exp(-x));
 }
 /** {@inheritDoc} */
 public double density(double x) {
   if (x < 0) {
     return 0;
   }
   return FastMath.exp(-x / mean) / mean;
 }
Exemple #28
0
 /** As described by Bernt Arne Ødegaard in Financial Numerical Recipes in C++. */
 private static double f(double x, double y, double aprime, double bprime, double c) {
   return FastMath.exp(
       aprime * (2d * x - aprime)
           + bprime * (2d * y - bprime)
           + 2d * c * (x - aprime) * (y - bprime));
 }