Example usage for java.lang Math tanh

List of usage examples for java.lang Math tanh

Introduction

In this page you can find the example usage for java.lang Math tanh.

Prototype

public static double tanh(double x) 

Source Link

Document

Returns the hyperbolic tangent of a double value.

Usage

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic sine./*w w  w. j  a  v a 2s .  c  om*/
 *
 * @param x the argument.
 * @return the sinh(x) = (exp(x)-exp(-x))/2 .
 */
static public BigDecimal sinh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sinh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        if (x.doubleValue() > 2.4) {
            /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
             */
            BigDecimal two = new BigDecimal(2);
            BigDecimal xhalf = x.divide(two);

            BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two);
            /* The error in the result is set by the error in x itself.
             * The first derivative of sinh(x) is cosh(x), so the absolute error
             * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
             */

            double eps = Math.tanh(x.doubleValue());
            MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps));

            return resul.round(mc);

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */
            BigDecimal resul = xhighpr;
            /* x^i */
            BigDecimal xpowi = xhighpr;
            /* 2i+1 factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The error in the result is set by the error in x itself.
             */

            double xUlpDbl = x.ulp().doubleValue();
            /* The error in the result is set by the error in x itself.
             * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
             * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
             * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
             */

            int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2;
            MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i or 2*i+1 overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is set by the error in x itself.
              */
            MathContext mc = new MathContext(x.precision());

            return resul.round(mc);

        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic tangent.//from  w  w w .j  a  va  2 s  .com
 *
 * @param x The argument.
 * @return The tanh(x) = sinh(x)/cosh(x).
 */
static public BigDecimal tanh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tanh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .
         */
        BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2)));
        /* The error in tanh x is err(x)/cosh^2(x).
         */

        double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0);
        MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps));

        return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc);

    }
}

From source file:org.netxilia.functions.MathFunctions.java

public double TANH(double number) {
    return Math.tanh(number);
}

From source file:org.renjin.primitives.MathGroup.java

@Deferrable
@Builtin/*from w w  w  . j  av  a2 s . c om*/
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double tanh(double x) {
    return Math.tanh(x);
}

From source file:test.uk.co.modularaudio.util.audio.math.FastMathTester.java

public void testTanhApproximation() {
    final float[] localFloatsToTest = new float[] { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f,
            1.0f, 1.1f, 1.2f, 10.0f, 100.0f, 200.0f, -200.0f, -100.0f, -10.0f, -1.0f, -0.5f, -0.1f, };

    final float[] localOutputFloats = new float[localFloatsToTest.length];

    for (int i = 0; i < localFloatsToTest.length; ++i) {
        final float ftt = localFloatsToTest[i];
        final float jmResult = (float) Math.tanh(ftt);
        localOutputFloats[i] = jmResult;
        final float fmResult = FastMath.fastApproxTanh(ftt);
        localOutputFloats[i] = fmResult;
        final float amResult = AudioMath.tanhNoClip(ftt);
        localOutputFloats[i] = amResult;

        log.debug("Sour(" + MathFormatter.slowFloatPrint(ftt, 12, true) + ")");
        log.debug("Java(" + MathFormatter.slowFloatPrint(jmResult, 12, true) + ")");
        log.debug("Appr(" + MathFormatter.slowFloatPrint(fmResult, 12, true) + ")");
        log.debug("AMAp(" + MathFormatter.slowFloatPrint(amResult, 12, true) + ")");
    }//from   w w  w .  j ava2 s  .  c  o m

    for (int i = 0; i < 100; ++i) {
        doOneCycle();
    }
}

From source file:test.uk.co.modularaudio.util.audio.math.FastMathTester.java

private void doOneCycle() {

    final long jnb = System.nanoTime();
    for (int i = 0; i < NUM_TEST_FLOATS; ++i) {
        outputFloats[i] = (float) Math.tanh(testFloats[i]);
    }//www.ja v a 2  s .  c om
    final long jna = System.nanoTime();
    final long fb = System.nanoTime();
    for (int i = 0; i < NUM_TEST_FLOATS; ++i) {
        outputFloats[i] = FastMath.fastApproxTanh(testFloats[i]);
    }
    final long fa = System.nanoTime();
    final long amb = System.nanoTime();
    for (int i = 0; i < NUM_TEST_FLOATS; ++i) {
        outputFloats[i] = AudioMath.tanhNoClip(testFloats[i]);
    }
    final long ama = System.nanoTime();
    final long javaTime = jna - jnb;
    final long fastTime = fa - fb;
    final long amTime = ama - amb;
    log.debug("Java nanos " + javaTime + " fast nanos " + fastTime + " audio math tan nanos " + amTime);
}

From source file:uk.ac.diamond.scisoft.analysis.dataset.Maths.java

/**
 * tanh - evaluate the tangent hyperbolic function on each element of the dataset
 * @param a/*  ww w.  j  a  v  a 2s. c  o m*/
 * @return dataset
 */
@SuppressWarnings("cast")
public static AbstractDataset tanh(final AbstractDataset a) {
    final int isize;
    final IndexIterator it = a.getIterator();
    AbstractDataset ds;
    final int dt = a.getDtype();

    switch (dt) {
    case AbstractDataset.INT8:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT32);
        final byte[] i8data = ((ByteDataset) a).data;
        final float[] oi8data = ((FloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final byte ix = i8data[it.index];
            float ox;
            ox = (float) (Math.tanh(ix));
            oi8data[i++] = ox;
        }
        break;
    case AbstractDataset.INT16:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT32);
        final short[] i16data = ((ShortDataset) a).data;
        final float[] oi16data = ((FloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final short ix = i16data[it.index];
            float ox;
            ox = (float) (Math.tanh(ix));
            oi16data[i++] = ox;
        }
        break;
    case AbstractDataset.INT32:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT64);
        final int[] i32data = ((IntegerDataset) a).data;
        final double[] oi32data = ((DoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final int ix = i32data[it.index];
            double ox;
            ox = (double) (Math.tanh(ix));
            oi32data[i++] = ox;
        }
        break;
    case AbstractDataset.INT64:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT64);
        final long[] i64data = ((LongDataset) a).data;
        final double[] oi64data = ((DoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final long ix = i64data[it.index];
            double ox;
            ox = (double) (Math.tanh(ix));
            oi64data[i++] = ox;
        }
        break;
    case AbstractDataset.ARRAYINT8:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT32);
        isize = a.getElementsPerItem();
        final byte[] ai8data = ((CompoundByteDataset) a).data;
        final float[] oai8data = ((CompoundFloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final byte ix = ai8data[it.index + j];
                float ox;
                ox = (float) (Math.tanh(ix));
                oai8data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.ARRAYINT16:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT32);
        isize = a.getElementsPerItem();
        final short[] ai16data = ((CompoundShortDataset) a).data;
        final float[] oai16data = ((CompoundFloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final short ix = ai16data[it.index + j];
                float ox;
                ox = (float) (Math.tanh(ix));
                oai16data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.ARRAYINT32:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT64);
        isize = a.getElementsPerItem();
        final int[] ai32data = ((CompoundIntegerDataset) a).data;
        final double[] oai32data = ((CompoundDoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final int ix = ai32data[it.index + j];
                double ox;
                ox = (double) (Math.tanh(ix));
                oai32data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.ARRAYINT64:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT64);
        isize = a.getElementsPerItem();
        final long[] ai64data = ((CompoundLongDataset) a).data;
        final double[] oai64data = ((CompoundDoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final long ix = ai64data[it.index + j];
                double ox;
                ox = (double) (Math.tanh(ix));
                oai64data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.FLOAT32:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT32);
        final float[] f32data = ((FloatDataset) a).data;
        final float[] of32data = ((FloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final float ix = f32data[it.index];
            float ox;
            ox = (float) (Math.tanh(ix));
            of32data[i++] = ox;
        }
        break;
    case AbstractDataset.FLOAT64:
        ds = AbstractDataset.zeros(a, AbstractDataset.FLOAT64);
        final double[] f64data = ((DoubleDataset) a).data;
        final double[] of64data = ((DoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final double ix = f64data[it.index];
            double ox;
            ox = (double) (Math.tanh(ix));
            of64data[i++] = ox;
        }
        break;
    case AbstractDataset.ARRAYFLOAT32:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT32);
        isize = a.getElementsPerItem();
        final float[] af32data = ((CompoundFloatDataset) a).data;
        final float[] oaf32data = ((CompoundFloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final float ix = af32data[it.index + j];
                float ox;
                ox = (float) (Math.tanh(ix));
                oaf32data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.ARRAYFLOAT64:
        ds = AbstractDataset.zeros(a, AbstractDataset.ARRAYFLOAT64);
        isize = a.getElementsPerItem();
        final double[] af64data = ((CompoundDoubleDataset) a).data;
        final double[] oaf64data = ((CompoundDoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            for (int j = 0; j < isize; j++) {
                final double ix = af64data[it.index + j];
                double ox;
                ox = (double) (Math.tanh(ix));
                oaf64data[i++] = ox;
            }
        }
        break;
    case AbstractDataset.COMPLEX64:
        ds = AbstractDataset.zeros(a, AbstractDataset.COMPLEX64);
        final float[] c64data = ((ComplexFloatDataset) a).data;
        final float[] oc64data = ((ComplexFloatDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final float ix = c64data[it.index];
            final float iy = c64data[it.index + 1];
            float tx;
            float ty;
            float tf;
            float ox;
            float oy;
            tx = (float) (2. * ix);
            ty = (float) (2. * iy);
            tf = (float) (1. / (Math.cos(tx) + Math.cosh(ty)));
            ox = (float) (tf * Math.sinh(tx));
            oy = (float) (tf * Math.sin(ty));
            oc64data[i++] = ox;
            oc64data[i++] = oy;
        }
        break;
    case AbstractDataset.COMPLEX128:
        ds = AbstractDataset.zeros(a, AbstractDataset.COMPLEX128);
        final double[] c128data = ((ComplexDoubleDataset) a).data;
        final double[] oc128data = ((ComplexDoubleDataset) ds).getData();
        for (int i = 0; it.hasNext();) {
            final double ix = c128data[it.index];
            final double iy = c128data[it.index + 1];
            double tx;
            double ty;
            double tf;
            double ox;
            double oy;
            tx = (double) (2. * ix);
            ty = (double) (2. * iy);
            tf = (double) (1. / (Math.cos(tx) + Math.cosh(ty)));
            ox = (double) (tf * Math.sinh(tx));
            oy = (double) (tf * Math.sin(ty));
            oc128data[i++] = ox;
            oc128data[i++] = oy;
        }
        break;
    default:
        throw new IllegalArgumentException(
                "tanh supports integer, compound integer, real, compound real, complex datasets only");
    }

    ds.setName(a.getName());
    addFunctionName(ds, "tanh");
    return ds;
}

From source file:uk.co.modularaudio.util.audio.dsp.LimiterTanh.java

public void filter(final float[] output, final int outOffset, final int length, final float[] kneeFloats,
        final int kneeTmpIndex, final float[] falloffFloats, final int falloffTmpIndex) {
    for (int s = 0; s < length; ++s) {
        final float knee = kneeFloats[kneeTmpIndex + s];
        final float value = output[outOffset + s];

        final int sign = (value < 0.0f ? -1 : 1);
        final float absVal = value * sign;

        if (knee >= 1.0f) {
            output[outOffset + s] = sign * (absVal < 1.0f ? absVal : 1.0f);
        } else if (absVal > knee) {
            final float upperLeg = 1.0f - knee;
            final float falloff = falloffFloats[falloffTmpIndex + s];

            final float amountOver = absVal - knee;
            final float normalisedAmountOver = (amountOver / upperLeg);

            final float normalisedScalor = normalisedAmountOver * falloff;

            final float mappedValue = (float) Math.tanh(normalisedScalor);

            final float scaledAmountOverValue = upperLeg * mappedValue;
            output[outOffset + s] = (knee + scaledAmountOverValue) * sign;
        }//from   w  w w .j av  a 2 s.com
    }
}

From source file:uk.co.modularaudio.util.audio.dsp.LimiterTanh.java

public void filter(final float[] output, final int outOffset, final int length) {
    if (knee >= 1.0f) {
        final int lastIndex = outOffset + length;
        for (int s = outOffset; s < lastIndex; ++s) {
            final float value = output[outOffset + s];

            final int sign = (value < 0.0f ? -1 : 1);
            final float absVal = value * sign;
            output[s] = sign * (absVal < 1.0f ? absVal : 1.0f);
        }/*from   w  w  w .j a  v a 2  s . c  o  m*/
    } else {
        for (int s = 0; s < length; ++s) {
            final float value = output[outOffset + s];

            final int sign = (value < 0.0f ? -1 : 1);
            final float absVal = value * sign;
            if (absVal > knee) {
                final float amountOver = absVal - kneeFloat;
                final float normalisedAmountOver = (amountOver / upperLegFloat);

                final float normalisedScalor = normalisedAmountOver * falloffFloat;

                final float mappedValue = (float) Math.tanh(normalisedScalor);

                final float scaledAmountOverValue = upperLegFloat * mappedValue;
                output[outOffset + s] = (kneeFloat + scaledAmountOverValue) * sign;
            }
        }
    }
}