signature:
public class LibUtils { /** * Calculates the current ARCHType
 * @ return The current ARCHType */
public static ARCHType calculateArch ( ) { } }

implementation: String osArch = System . getProperty ( "os.arch" ) ; osArch = osArch . toLowerCase ( Locale . ENGLISH ) ; if ( osArch . equals ( "i386" ) || osArch . equals ( "x86" ) || osArch . equals ( "i686" ) ) { return ARCHType . X86 ; } if ( osArch . startsWith ( "amd64" ) || osArch . startsWith ( "x86_64" ) ) { return ARCHType . X86_64 ; } if ( osArch . equals ( "ppc" ) || osArch . equals ( "powerpc" ) ) { return ARCHType . PPC ; } if ( osArch . startsWith ( "ppc" ) ) { return ARCHType . PPC_64 ; } if ( osArch . startsWith ( "sparc" ) ) { return ARCHType . SPARC ; } if ( osArch . startsWith ( "arm" ) ) { return ARCHType . ARM ; } if ( osArch . startsWith ( "mips" ) ) { return ARCHType . MIPS ; } if ( osArch . contains ( "risc" ) ) { return ARCHType . RISC ; } return ARCHType . UNKNOWN ;


signature:
public class Nd4jKafkaProducer { /** * Publish to a kafka topic
 * based on the connection information
 * @ param arr */
public void publish ( INDArray arr ) { } }

implementation: if ( producerTemplate == null ) producerTemplate = camelContext . createProducerTemplate ( ) ; producerTemplate . sendBody ( "direct:start" , arr ) ;


signature:
public class InstrumentationApplication { /** * Start the server */
public void start ( ) { } }

implementation: try { InputStream is = new ClassPathResource ( resourcePath , InstrumentationApplication . class . getClassLoader ( ) ) . getInputStream ( ) ; File tmpConfig = new File ( resourcePath ) ; if ( ! tmpConfig . getParentFile ( ) . exists ( ) ) tmpConfig . getParentFile ( ) . mkdirs ( ) ; BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( tmpConfig ) ) ; IOUtils . copy ( is , bos ) ; bos . flush ( ) ; run ( new String [ ] { "server" , tmpConfig . getAbsolutePath ( ) } ) ; tmpConfig . deleteOnExit ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class DefaultDataBufferFactory { /** * Create a data buffer based on the
 * given pointer , data buffer opType ,
 * and length of the buffer
 * @ param pointer the pointer to use
 * @ param type the opType of buffer
 * @ param length the length of the buffer
 * @ param indexer the indexer for the pointer
 * @ return the data buffer
 * backed by this pointer with the given
 * opType and length . */
@ Override public DataBuffer create ( Pointer pointer , DataBuffer . Type type , long length , Indexer indexer ) { } }

implementation: switch ( type ) { case INT : return new IntBuffer ( pointer , indexer , length ) ; case DOUBLE : return new DoubleBuffer ( pointer , indexer , length ) ; case FLOAT : return new FloatBuffer ( pointer , indexer , length ) ; case LONG : return new LongBuffer ( pointer , indexer , length ) ; } throw new IllegalArgumentException ( "Invalid opType " + type ) ;


signature:
public class DefaultOpExecutioner { /** * This method checks if any Op operand has data opType of INT , and throws exception if any .
 * @ param op */
protected void interceptIntDataType ( Op op ) { } }

implementation:
// FIXME : Remove this method , after we ' ll add support for < int > dtype operations
if ( op . x ( ) != null && op . x ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( "Op.X contains INT data. Operations on INT dataType are not supported yet" ) ; if ( op . z ( ) != null && op . z ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( "Op.Z contains INT data. Operations on INT dataType are not supported yet" ) ; if ( op . y ( ) != null && op . y ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( "Op.Y contains INT data. Operations on INT dataType are not supported yet." ) ;


signature:
public class BaseComplexFloat { /** * Add two complex numbers in - place
 * @ param c
 * @ param result */
@ Override public IComplexNumber addi ( IComplexNumber c , IComplexNumber result ) { } }

implementation: return result . set ( result . realComponent ( ) . floatValue ( ) + c . realComponent ( ) . floatValue ( ) , result . imaginaryComponent ( ) . floatValue ( ) + c . imaginaryComponent ( ) . floatValue ( ) ) ;


signature:
public class BaseComplexFloat { /** * Multiply two complex numbers , inplace
 * @ param c
 * @ param result */
@ Override public IComplexNumber muli ( IComplexNumber c , IComplexNumber result ) { } }

implementation: float newR = realComponent ( ) * c . realComponent ( ) . floatValue ( ) - imaginaryComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ; float newI = realComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) + imaginaryComponent ( ) * c . realComponent ( ) . floatValue ( ) ; return result . set ( newR , newI ) ;


signature:
public class BaseComplexFloat { /** * Divide two complex numbers , in - place
 * @ param c
 * @ param result */
@ Override public IComplexNumber divi ( IComplexNumber c , IComplexNumber result ) { } }

implementation: float d = c . realComponent ( ) . floatValue ( ) * c . realComponent ( ) . floatValue ( ) + c . imaginaryComponent ( ) . floatValue ( ) * c . imaginaryComponent ( ) . floatValue ( ) ; float newR = ( realComponent ( ) * c . realComponent ( ) . floatValue ( ) + imaginaryComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ) / d ; float newI = ( imaginaryComponent ( ) * c . realComponent ( ) . floatValue ( ) - realComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ) / d ; return result . set ( newR , newI ) ;


signature:
public class CompressedDataBuffer { /** * Drop - in replacement wrapper for BaseDataBuffer . read ( ) method , aware of CompressedDataBuffer
 * @ param s
 * @ return */
public static DataBuffer readUnknown ( DataInputStream s , long length ) { } }

implementation:
DataBuffer buffer = Nd4j . createBuffer ( length ) ; buffer . read ( s ) ; // if buffer is uncompressed , it ' ll be valid buffer , so we ' ll just return it
if ( buffer . dataType ( ) != Type . COMPRESSED ) return buffer ; else { try { // if buffer is compressed one , we ' ' ll restore it here
String compressionAlgorithm = s . readUTF ( ) ; long compressedLength = s . readLong ( ) ; long originalLength = s . readLong ( ) ; long numberOfElements = s . readLong ( ) ; byte [ ] temp = new byte [ ( int ) compressedLength ] ; for ( int i = 0 ; i < compressedLength ; i ++ ) { temp [ i ] = s . readByte ( ) ; } Pointer pointer = new BytePointer ( temp ) ; CompressionDescriptor descriptor = new CompressionDescriptor ( ) ; descriptor . setCompressedLength ( compressedLength ) ; descriptor . setCompressionAlgorithm ( compressionAlgorithm ) ; descriptor . setOriginalLength ( originalLength ) ; descriptor . setNumberOfElements ( numberOfElements ) ; return new CompressedDataBuffer ( pointer , descriptor ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }


signature:
public class DistributedAssignMessage { /** * This method assigns specific value to either specific row , or whole array .
 * Array is identified by key */
@ Override public void processMessage ( ) { } }

implementation:
if ( payload != null ) { // we ' re assigning array
if ( storage . arrayExists ( key ) && storage . getArray ( key ) . length ( ) == payload . length ( ) ) storage . getArray ( key ) . assign ( payload ) ; else storage . setArray ( key , payload ) ; } else { // we ' re assigning number to row
if ( index >= 0 ) { if ( storage . getArray ( key ) == null ) throw new RuntimeException ( "Init wasn't called before for key [" + key + "]" ) ; storage . getArray ( key ) . getRow ( index ) . assign ( value ) ; } else storage . getArray ( key ) . assign ( value ) ; }


signature:
public class DifferentialFunctionFactory { /** * Local response normalization operation .
 * @ param inputs the inputs to lrn
 * @ param lrnConfig the configuration
 * @ return */
public SDVariable localResponseNormalization ( SDVariable inputs , LocalResponseNormalizationConfig lrnConfig ) { } }

implementation: LocalResponseNormalization lrn = LocalResponseNormalization . builder ( ) . inputFunctions ( new SDVariable [ ] { inputs } ) . sameDiff ( sameDiff ( ) ) . config ( lrnConfig ) . build ( ) ; return lrn . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Conv1d operation .
 * @ param inputs the inputs to conv1d
 * @ param conv1DConfig the configuration
 * @ return */
public SDVariable conv1d ( SDVariable [ ] inputs , Conv1DConfig conv1DConfig ) { } }

implementation: Conv1D conv1D = Conv1D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv1DConfig ) . build ( ) ; return conv1D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Conv2d operation .
 * @ param inputs the inputs to conv2d
 * @ param conv2DConfig the configuration
 * @ return */
public SDVariable conv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { } }

implementation: Conv2D conv2D = Conv2D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv2DConfig ) . build ( ) ; return conv2D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Average pooling 2d operation .
 * @ param inputs the inputs to pooling
 * @ param pooling2DConfig the configuration
 * @ return */
public SDVariable avgPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { } }

implementation: AvgPooling2D avgPooling2D = AvgPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return avgPooling2D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Max pooling 2d operation .
 * @ param inputs the inputs to pooling
 * @ param pooling2DConfig the configuration
 * @ return */
public SDVariable maxPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { } }

implementation: MaxPooling2D maxPooling2D = MaxPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return maxPooling2D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Avg pooling 3d operation .
 * @ param inputs the inputs to pooling
 * @ param pooling3DConfig the configuration
 * @ return */
public SDVariable avgPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { } }

implementation: Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . AVG ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Max pooling 3d operation .
 * @ param inputs the inputs to pooling
 * @ param pooling3DConfig the configuration
 * @ return */
public SDVariable maxPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { } }

implementation: Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . MAX ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Separable Conv2d operation .
 * @ param inputs the inputs to conv2d
 * @ param conv2DConfig the configuration
 * @ return */
public SDVariable sconv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { } }

implementation: SConv2D sconv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( conv2DConfig ) . build ( ) ; return sconv2D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Depthwise Conv2d operation . This is just separable convolution with
 * only the depth - wise weights specified .
 * @ param inputs the inputs to conv2d
 * @ param depthConv2DConfig the configuration
 * @ return */
public SDVariable depthWiseConv2d ( SDVariable [ ] inputs , Conv2DConfig depthConv2DConfig ) { } }

implementation: SConv2D depthWiseConv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( depthConv2DConfig ) . build ( ) ; return depthWiseConv2D . outputVariables ( ) [ 0 ] ;


signature:
public class DifferentialFunctionFactory { /** * Deconv2d operation .
 * @ param inputs the inputs to conv2d
 * @ param deconv2DConfig the configuration
 * @ return */
public SDVariable deconv2d ( SDVariable [ ] inputs , DeConv2DConfig deconv2DConfig ) { } }

implementation: DeConv2D deconv2D = DeConv2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( deconv2DConfig ) . build ( ) ; return deconv2D . outputVariables ( ) [ 0 ] ;


signature:
public class PCA { /** * Returns the covariance matrix of a data set of many records , each with N features .
 * It also returns the average values , which are usually going to be important since in this
 * version , all modes are centered around the mean . It ' s a matrix that has elements that are
 * expressed as average dx _ i * dx _ j ( used in procedure ) or average x _ i * x _ j - average x _ i * average x _ j
 * @ param in A matrix of vectors of fixed length N ( N features ) on each row
 * @ return INDArray [ 2 ] , an N x N covariance matrix is element 0 , and the average values is element 1. */
public static INDArray [ ] covarianceMatrix ( INDArray in ) { } }

implementation: long dlength = in . rows ( ) ; long vlength = in . columns ( ) ; INDArray sum = Nd4j . create ( vlength ) ; INDArray product = Nd4j . create ( vlength , vlength ) ; for ( int i = 0 ; i < vlength ; i ++ ) sum . getColumn ( i ) . assign ( in . getColumn ( i ) . sumNumber ( ) . doubleValue ( ) / dlength ) ; for ( int i = 0 ; i < dlength ; i ++ ) { INDArray dx1 = in . getRow ( i ) . sub ( sum ) ; product . addi ( dx1 . reshape ( vlength , 1 ) . mmul ( dx1 . reshape ( 1 , vlength ) ) ) ; } product . divi ( dlength ) ; return new INDArray [ ] { product , sum } ;


signature:
public class PCA { /** * Calculates the principal component vectors and their eigenvalues ( lambda ) for the covariance matrix .
 * The result includes two things : the eigenvectors ( modes ) as result [ 0 ] and the eigenvalues ( lambda )
 * as result [ 1 ] .
 * @ param cov The covariance matrix ( calculated with the covarianceMatrix ( in ) method )
 * @ return Array INDArray [ 2 ] " result " . The principal component vectors in decreasing flexibility are
 * the columns of element 0 and the eigenvalues are element 1. */
public static INDArray [ ] principalComponents ( INDArray cov ) { } }

implementation: assert cov . rows ( ) == cov . columns ( ) ; INDArray [ ] result = new INDArray [ 2 ] ; result [ 0 ] = Nd4j . eye ( cov . rows ( ) ) ; result [ 1 ] = Eigen . symmetricGeneralizedEigenvalues ( result [ 0 ] , cov , true ) ; return result ;


signature:
public class OpProfiler { /** * This method resets all counters */
public void reset ( ) { } }

implementation: invocationsCount . set ( 0 ) ; classAggergator . reset ( ) ; longAggergator . reset ( ) ; classCounter . reset ( ) ; opCounter . reset ( ) ; classPairsCounter . reset ( ) ; opPairsCounter . reset ( ) ; matchingCounter . reset ( ) ; matchingCounterDetailed . reset ( ) ; matchingCounterInverted . reset ( ) ; methodsAggregator . reset ( ) ; scalarAggregator . reset ( ) ; nonEwsAggregator . reset ( ) ; stridedAggregator . reset ( ) ; tadNonEwsAggregator . reset ( ) ; tadStridedAggregator . reset ( ) ; mixedOrderAggregator . reset ( ) ; blasAggregator . reset ( ) ; blasOrderCounter . reset ( ) ; orderCounter . reset ( ) ; listeners . clear ( ) ;


signature:
public class OpProfiler { /** * This method returns op class opName
 * @ param op
 * @ return */
protected String getOpClass ( Op op ) { } }

implementation: if ( op instanceof ScalarOp ) { return "ScalarOp" ; } else if ( op instanceof MetaOp ) { return "MetaOp" ; } else if ( op instanceof GridOp ) { return "GridOp" ; } else if ( op instanceof BroadcastOp ) { return "BroadcastOp" ; } else if ( op instanceof RandomOp ) { return "RandomOp" ; } else if ( op instanceof Accumulation ) { return "AccumulationOp" ; } else if ( op instanceof TransformOp ) { if ( op . y ( ) == null ) { return "TransformOp" ; } else return "PairWiseTransformOp" ; } else if ( op instanceof IndexAccumulation ) { return "IndexAccumulationOp" ; } else if ( op instanceof CustomOp ) { return "CustomOp" ; } else return "Unknown Op calls" ;


signature:
public class CpuNDArrayFactory { /** * Create a complex ndarray from the passed in indarray
 * @ param arrs the arr to wrap
 * @ param shape
 * @ return the complex ndarray with the specified ndarray as the
 * real components */
@ Override public IComplexNDArray createComplex ( List < IComplexNDArray > arrs , int [ ] shape ) { } }

implementation: return new ComplexNDArray ( arrs , shape ) ;


signature:
public class SDVariable { /** * Allocate and return a new array
 * based on the vertex id and weight initialization .
 * @ return the allocated array */
public INDArray storeAndAllocateNewArray ( ) { } }

implementation: val shape = sameDiff . getShapeForVarName ( getVarName ( ) ) ; if ( getArr ( ) != null && Arrays . equals ( getArr ( ) . shape ( ) , shape ) ) return getArr ( ) ; if ( varName == null ) throw new ND4JIllegalStateException ( "Unable to store array for null variable name!" ) ; if ( shape == null ) { throw new ND4JIllegalStateException ( "Unable to allocate new array. No shape found for variable " + varName ) ; } val arr = getWeightInitScheme ( ) . create ( shape ) ; sameDiff . putArrayForVarName ( getVarName ( ) , arr ) ; return arr ;


signature:
public class SDVariable { /** * A getter for the allocated ndarray
 * with this { @ link SDVariable } .
 * This getter will lazy initialize an array if one is not found
 * based on the associated shape and { @ link WeightInitScheme }
 * if neither are found , an { @ link ND4JIllegalStateException }
 * is thrown .
 * If a { @ link DifferentialFunction } is defined , note that
 * its getArr ( ) method is called instead .
 * @ return the { @ link INDArray } associated with this variable . */
public INDArray getArr ( ) { } }

implementation:
if ( sameDiff . arrayAlreadyExistsForVarName ( getVarName ( ) ) ) return sameDiff . getArrForVarName ( getVarName ( ) ) ; // initialize value if it ' s actually a scalar constant ( zero or 1 typically . . . )
if ( getScalarValue ( ) != null && ArrayUtil . prod ( getShape ( ) ) == 1 ) { INDArray arr = Nd4j . valueArrayOf ( getShape ( ) , getScalarValue ( ) . doubleValue ( ) ) ; sameDiff . associateArrayWithVariable ( arr , this ) ; } else if ( sameDiff . getShapeForVarName ( getVarName ( ) ) == null ) return null ; else { INDArray newAlloc = getWeightInitScheme ( ) . create ( sameDiff . getShapeForVarName ( getVarName ( ) ) ) ; sameDiff . associateArrayWithVariable ( newAlloc , this ) ; } return sameDiff . getArrForVarName ( getVarName ( ) ) ;


signature:
public class SDVariable { /** * Returns the shape of this variable
 * @ return */
public long [ ] getShape ( ) { } }

implementation: long [ ] initialShape = sameDiff . getShapeForVarName ( getVarName ( ) ) ; if ( initialShape == null ) { val arr = getArr ( ) ; if ( arr != null ) return arr . shape ( ) ; } return initialShape ;


signature:
public class SDVariable { /** * Evaluate the result of this variable
 * @ return */
public INDArray eval ( ) { } }

implementation: SameDiff exec = sameDiff . dup ( ) ; exec . defineFunction ( "output" , new SameDiff . SameDiffFunctionDefinition ( ) { @ Override public SDVariable [ ] define ( SameDiff sameDiff , Map < String , INDArray > inputs , SDVariable [ ] variableInputs ) { return new SDVariable [ ] { SDVariable . this } ; } } ) ; SDVariable output = exec . invokeFunctionOn ( "output" , exec ) ; return output . getSameDiff ( ) . execAndEndResult ( ) ;


signature:
public class AbstractCompressor { /** * This method creates compressed INDArray from Java double array , skipping usual INDArray instantiation routines
 * @ param data
 * @ param shape
 * @ param order
 * @ return */
@ Override public INDArray compress ( double [ ] data , int [ ] shape , char order ) { } }

implementation: DoublePointer pointer = new DoublePointer ( data ) ; DataBuffer shapeInfo = Nd4j . getShapeInfoProvider ( ) . createShapeInformation ( shape , order ) . getFirst ( ) ; DataBuffer buffer = compressPointer ( DataBuffer . TypeEx . DOUBLE , pointer , data . length , 8 ) ; return Nd4j . createArrayFromShapeBuffer ( buffer , shapeInfo ) ;


signature:
public class ComplexNDArrayUtil { /** * Returns the exponential of a complex ndarray
 * @ param toExp the ndarray to convert
 * @ return the exponential of the specified
 * ndarray */
public static IComplexNDArray expi ( IComplexNDArray toExp ) { } }

implementation: IComplexNDArray flattened = toExp . ravel ( ) ; for ( int i = 0 ; i < flattened . length ( ) ; i ++ ) { IComplexNumber n = flattened . getComplex ( i ) ; flattened . put ( i , Nd4j . scalar ( ComplexUtil . exp ( n ) ) ) ; } return flattened . reshape ( toExp . shape ( ) ) ;


signature:
public class ComplexNDArrayUtil { /** * Center an array
 * @ param arr the arr to center
 * @ param shape the shape of the array
 * @ return the center portion of the array based on the
 * specified shape */
public static IComplexNDArray center ( IComplexNDArray arr , long [ ] shape ) { } }

implementation: if ( arr . length ( ) < ArrayUtil . prod ( shape ) ) return arr ; for ( int i = 0 ; i < shape . length ; i ++ ) if ( shape [ i ] < 1 ) shape [ i ] = 1 ; INDArray shapeMatrix = NDArrayUtil . toNDArray ( shape ) ; INDArray currShape = NDArrayUtil . toNDArray ( arr . shape ( ) ) ; INDArray startIndex = Transforms . floor ( currShape . sub ( shapeMatrix ) . divi ( Nd4j . scalar ( 2 ) ) ) ; INDArray endIndex = startIndex . add ( shapeMatrix ) ; INDArrayIndex [ ] indexes = Indices . createFromStartAndEnd ( startIndex , endIndex ) ; if ( shapeMatrix . length ( ) > 1 ) return arr . get ( indexes ) ; else { IComplexNDArray ret = Nd4j . createComplex ( new int [ ] { ( int ) shapeMatrix . getDouble ( 0 ) } ) ; int start = ( int ) startIndex . getDouble ( 0 ) ; int end = ( int ) endIndex . getDouble ( 0 ) ; int count = 0 ; for ( int i = start ; i < end ; i ++ ) { ret . putScalar ( count ++ , arr . getComplex ( i ) ) ; } return ret ; }


signature:
public class ComplexNDArrayUtil { /** * Truncates an ndarray to the specified shape .
 * If the shape is the same or greater , it just returns
 * the original array
 * @ param nd the ndarray to truncate
 * @ param n the number of elements to truncate to
 * @ return the truncated ndarray */
public static IComplexNDArray truncate ( IComplexNDArray nd , int n , int dimension ) { } }

implementation: if ( nd . isVector ( ) ) { IComplexNDArray truncated = Nd4j . createComplex ( new int [ ] { 1 , n } ) ; for ( int i = 0 ; i < n ; i ++ ) truncated . putScalar ( i , nd . getComplex ( i ) ) ; return truncated ; } if ( nd . size ( dimension ) > n ) { long [ ] shape = ArrayUtil . copy ( nd . shape ( ) ) ; shape [ dimension ] = n ; IComplexNDArray ret = Nd4j . createComplex ( shape ) ; IComplexNDArray ndLinear = nd . linearView ( ) ; IComplexNDArray retLinear = ret . linearView ( ) ; for ( int i = 0 ; i < ret . length ( ) ; i ++ ) retLinear . putScalar ( i , ndLinear . getComplex ( i ) ) ; return ret ; } return nd ;


signature:
public class ComplexNDArrayUtil { /** * Pads an ndarray with zeros
 * @ param nd the ndarray to pad
 * @ param targetShape the the new shape
 * @ return the padded ndarray */
public static IComplexNDArray padWithZeros ( IComplexNDArray nd , long [ ] targetShape ) { } }

implementation:
if ( Arrays . equals ( nd . shape ( ) , targetShape ) ) return nd ; // no padding required
if ( ArrayUtil . prod ( nd . shape ( ) ) >= ArrayUtil . prod ( targetShape ) ) return nd ; IComplexNDArray ret = Nd4j . createComplex ( targetShape ) ; INDArrayIndex [ ] targetShapeIndex = NDArrayIndex . createCoveringShape ( nd . shape ( ) ) ; ret . put ( targetShapeIndex , nd ) ; return ret ;


signature:
public class SparseBaseLevel1 { /** * Find the index of the element with maximum absolute value
 * @ param arr a vector
 * @ return the index of the element with maximum absolute value */
@ Override public int iamax ( INDArray arr ) { } }

implementation: switch ( arr . data ( ) . dataType ( ) ) { case DOUBLE : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , arr ) ; return idamax ( arr . length ( ) , arr , 1 ) ; case FLOAT : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , arr ) ; return isamax ( arr . length ( ) , arr , 1 ) ; case HALF : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . HALF , arr ) ; return ihamax ( arr . length ( ) , arr , 1 ) ; default : } throw new UnsupportedOperationException ( ) ;


signature:
public class DeviceLocalNDArray { /** * This method duplicates array , and stores it to all devices
 * @ param array */
public void broadcast ( INDArray array ) { } }

implementation:
if ( array == null ) return ; Nd4j . getExecutioner ( ) . commit ( ) ; int numDevices = Nd4j . getAffinityManager ( ) . getNumberOfDevices ( ) ; for ( int i = 0 ; i < numDevices ; i ++ ) { // if current thread equal to this device - we just save it , without duplication
if ( Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) == i ) { set ( i , array ) ; } else { set ( i , Nd4j . getAffinityManager ( ) . replicateToDevice ( i , array ) ) ; } }


signature:
public class DistributedVectorMessage { /** * This method will be started in context of executor , either Shard , Client or Backup node */
@ Override public void processMessage ( ) { } }

implementation: VectorAggregation aggregation = new VectorAggregation ( rowIndex , ( short ) voidConfiguration . getNumberOfShards ( ) , shardIndex , storage . getArray ( key ) . getRow ( rowIndex ) . dup ( ) ) ; aggregation . setOriginatorId ( this . getOriginatorId ( ) ) ; transport . sendMessage ( aggregation ) ;


signature:
public class BigDecimalMath { /** * Euler ’ s constant .
 * @ param mc The required precision of the result .
 * @ return 3.14159 . . . */
static public BigDecimal pi ( final MathContext mc ) { } }

implementation:
/* look it up if possible */
if ( mc . getPrecision ( ) < PI . precision ( ) ) { return PI . round ( mc ) ; } else { /* Broadhurst \ protect \ vrule width0pt \ protect \ href { http : / / arxiv . org / abs / math / 9803067 } { arXiv : math / 9803067} */
int [ ] a = { 1 , 0 , 0 , - 1 , - 1 , - 1 , 0 , 0 } ; BigDecimal S = broadhurstBBP ( 1 , 1 , a , mc ) ; return multiplyRound ( S , 8 ) ; }


signature:
public class BigDecimalMath { /** * Euler - Mascheroni constant .
 * @ param mc The required precision of the result .
 * @ return 0.577 . . . */
static public BigDecimal gamma ( MathContext mc ) { } }

implementation:
/* look it up if possible */
if ( mc . getPrecision ( ) < GAMMA . precision ( ) ) { return GAMMA . round ( mc ) ; } else { double eps = prec2err ( 0.577 , mc . getPrecision ( ) ) ; /* Euler - Stieltjes as shown in Dilcher , Aequat Math 48 ( 1 ) ( 1994 ) 55-85
 14 */
MathContext mcloc = new MathContext ( 2 + mc . getPrecision ( ) ) ; BigDecimal resul = BigDecimal . ONE ; resul = resul . add ( log ( 2 , mcloc ) ) ; resul = resul . subtract ( log ( 3 , mcloc ) ) ; /* how many terms : zeta - 1 falls as 1/2 ^ ( 2n + 1 ) , so the
 * terms drop faster than 1/2 ^ ( 4n + 2 ) . Set 1/2 ^ ( 4kmax + 2 ) < eps .
 * Leading term zeta ( 3 ) / ( 4 ^ 1*3 ) is 0.017 . Leading zeta ( 3 ) is 1.2 . Log ( 2 ) is 0.7 */
int kmax = ( int ) ( ( Math . log ( eps / 0.7 ) - 2. ) / 4. ) ; mcloc = new MathContext ( 1 + err2prec ( 1.2 , eps / kmax ) ) ; for ( int n = 1 ; ; n ++ ) { /* zeta is close to 1 . Division of zeta - 1 through
 * 4 ^ n * ( 2n + 1 ) means divion through roughly 2 ^ ( 2n + 1) */
BigDecimal c = zeta ( 2 * n + 1 , mcloc ) . subtract ( BigDecimal . ONE ) ; BigInteger fourn = BigInteger . valueOf ( 2 * n + 1 ) ; fourn = fourn . shiftLeft ( 2 * n ) ; c = divideRound ( c , fourn ) ; resul = resul . subtract ( c ) ; if ( c . doubleValue ( ) < 0.1 * eps ) { break ; } } return resul . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The square root .
 * @ param x the non - negative argument .
 * @ return the square root of the BigDecimal rounded to the precision implied by x . */
static public BigDecimal sqrt ( final BigDecimal x ) { } }

implementation: if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( "negative argument " + x . toString ( ) + " of square root" ) ; } return root ( 2 , x ) ;


signature:
public class BigDecimalMath { /** * The cube root .
 * @ param x The argument .
 * @ return The cubic root of the BigDecimal rounded to the precision implied by x .
 * The sign of the result is the sign of the argument . */
static public BigDecimal cbrt ( final BigDecimal x ) { } }

implementation: if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return root ( 3 , x . negate ( ) ) . negate ( ) ; } else { return root ( 3 , x ) ; }


signature:
public class BigDecimalMath { /** * The integer root .
 * @ param n the positive argument .
 * @ param x the non - negative argument .
 * @ return The n - th root of the BigDecimal rounded to the precision implied by x , x ^ ( 1 / n ) . */
static public BigDecimal root ( final int n , final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( "negative argument " + x . toString ( ) + " of root" ) ; } if ( n <= 0 ) { throw new ArithmeticException ( "negative power " + n + " of root" ) ; } if ( n == 1 ) { return x ; } /* start the computation from a double precision estimate */
BigDecimal s = new BigDecimal ( Math . pow ( x . doubleValue ( ) , 1.0 / n ) ) ; /* this creates nth with nominal precision of 1 digit */
final BigDecimal nth = new BigDecimal ( n ) ; /* Specify an internal accuracy within the loop which is
 * slightly larger than what is demanded by ’ eps ’ below . */
final BigDecimal xhighpr = scalePrec ( x , 2 ) ; MathContext mc = new MathContext ( 2 + x . precision ( ) ) ; /* Relative accuracy of the result is eps . */
final double eps = x . ulp ( ) . doubleValue ( ) / ( 2 * n * x . doubleValue ( ) ) ; for ( ; ; ) { /* s = s - ( s / n - x / n / s ^ ( n - 1 ) ) = s - ( s - x / s ^ ( n - 1 ) ) / n ; test correction s / n - x / s for being
 * smaller than the precision requested . The relative correction is ( 1 - x / s ^ n ) / n , */
BigDecimal c = xhighpr . divide ( s . pow ( n - 1 ) , mc ) ; c = s . subtract ( c ) ; MathContext locmc = new MathContext ( c . precision ( ) ) ; c = c . divide ( nth , locmc ) ; s = s . subtract ( c ) ; if ( Math . abs ( c . doubleValue ( ) / s . doubleValue ( ) ) < eps ) { break ; } } return s . round ( new MathContext ( err2prec ( eps ) ) ) ;


signature:
public class BigDecimalMath { /** * The hypotenuse .
 * @ param x the first argument .
 * @ param y the second argument .
 * @ return the square root of the sum of the squares of the two arguments , sqrt ( x ^ 2 + y ^ 2 ) . */
static public BigDecimal hypot ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
/* compute x ^ 2 + y ^ 2 */
BigDecimal z = x . pow ( 2 ) . add ( y . pow ( 2 ) ) ; /* truncate to the precision set by x and y . Absolute error = 2 * x * xerr + 2 * y * yerr ,
 * where the two errors are 1/2 of the ulp ’ s . Two intermediate protectio digits . */
BigDecimal zerr = x . abs ( ) . multiply ( x . ulp ( ) ) . add ( y . abs ( ) . multiply ( y . ulp ( ) ) ) ; MathContext mc = new MathContext ( 2 + err2prec ( z , zerr ) ) ; /* Pull square root */
z = sqrt ( z . round ( mc ) ) ; /* Final rounding . Absolute error in the square root is ( y * yerr + x * xerr ) / z , where zerr holds 2 * ( x * xerr + y * yerr ) . */
mc = new MathContext ( err2prec ( z . doubleValue ( ) , 0.5 * zerr . doubleValue ( ) / z . doubleValue ( ) ) ) ; return z . round ( mc ) ;


signature:
public class BigDecimalMath { /** * The hypotenuse .
 * @ param n the first argument .
 * @ param x the second argument .
 * @ return the square root of the sum of the squares of the two arguments , sqrt ( n ^ 2 + x ^ 2 ) . */
static public BigDecimal hypot ( final int n , final BigDecimal x ) { } }

implementation:
/* compute n ^ 2 + x ^ 2 in infinite precision */
BigDecimal z = ( new BigDecimal ( n ) ) . pow ( 2 ) . add ( x . pow ( 2 ) ) ; /* Truncate to the precision set by x . Absolute error = in z ( square of the result ) is | 2 * x * xerr | ,
 * where the error is 1/2 of the ulp . Two intermediate protection digits .
 * zerr is a signed value , but used only in conjunction with err2prec ( ) , so this feature does not harm . */
double zerr = x . doubleValue ( ) * x . ulp ( ) . doubleValue ( ) ; MathContext mc = new MathContext ( 2 + err2prec ( z . doubleValue ( ) , zerr ) ) ; /* Pull square root */
z = sqrt ( z . round ( mc ) ) ; /* Final rounding . Absolute error in the square root is x * xerr / z , where zerr holds 2 * x * xerr . */
mc = new MathContext ( err2prec ( z . doubleValue ( ) , 0.5 * zerr / z . doubleValue ( ) ) ) ; return z . round ( mc ) ;


signature:
public class BigDecimalMath { /** * The exponential function .
 * @ param x the argument .
 * @ return exp ( x ) .
 * The precision of the result is implicitly defined by the precision in the argument .
 * 16
 * In particular this means that " Invalid Operation " errors are thrown if catastrophic
 * cancellation of digits causes the result to have no valid digits left . */
static public BigDecimal exp ( BigDecimal x ) { } }

implementation:
/* To calculate the value if x is negative , use exp ( - x ) = 1 / exp ( x ) */
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { final BigDecimal invx = exp ( x . negate ( ) ) ; /* Relative error in inverse of invx is the same as the relative errror in invx .
 * This is used to define the precision of the result . */
MathContext mc = new MathContext ( invx . precision ( ) ) ; return BigDecimal . ONE . divide ( invx , mc ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { /* recover the valid number of digits from x . ulp ( ) , if x hits the
 * zero . The x . precision ( ) is 1 then , and does not provide this information . */
return scalePrec ( BigDecimal . ONE , - ( int ) ( Math . log10 ( x . ulp ( ) . doubleValue ( ) ) ) ) ; } else { /* Push the number in the Taylor expansion down to a small
 * value where TAYLOR _ NTERM terms will do . If x < 1 , the n - th term is of the order
 * x ^ n / n ! , and equal to both the absolute and relative error of the result
 * since the result is close to 1 . The x . ulp ( ) sets the relative and absolute error
 * of the result , as estimated from the first Taylor term .
 * We want x ^ TAYLOR _ NTERM / TAYLOR _ NTERM ! < x . ulp , which is guaranteed if
 * x ^ TAYLOR _ NTERM < TAYLOR _ NTERM * ( TAYLOR _ NTERM - 1 ) * . . . * x . ulp . */
final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; if ( Math . pow ( xDbl , TAYLOR_NTERM ) < TAYLOR_NTERM * ( TAYLOR_NTERM - 1.0 ) * ( TAYLOR_NTERM - 2.0 ) * xUlpDbl ) { /* Add TAYLOR _ NTERM terms of the Taylor expansion ( Euler ’ s sum formula ) */
BigDecimal resul = BigDecimal . ONE ; /* x ^ i */
BigDecimal xpowi = BigDecimal . ONE ; /* i factorial */
BigInteger ifac = BigInteger . ONE ; /* TAYLOR _ NTERM terms to be added means we move x . ulp ( ) to the right
 * for each power of 10 in TAYLOR _ NTERM , so the addition won ’ t add noise beyond
 * what ’ s already in x . */
MathContext mcTay = new MathContext ( err2prec ( 1. , xUlpDbl / TAYLOR_NTERM ) ) ; for ( int i = 1 ; i <= TAYLOR_NTERM ; i ++ ) { ifac = ifac . multiply ( BigInteger . valueOf ( i ) ) ; xpowi = xpowi . multiply ( x ) ; final BigDecimal c = xpowi . divide ( new BigDecimal ( ifac ) , mcTay ) ; resul = resul . add ( c ) ; if ( Math . abs ( xpowi . doubleValue ( ) ) < i && Math . abs ( c . doubleValue ( ) ) < 0.5 * xUlpDbl ) { break ; } } /* exp ( x + deltax ) = exp ( x ) ( 1 + deltax ) if deltax is < < 1 . So the relative error
 * in the result equals the absolute error in the argument . */
MathContext mc = new MathContext ( err2prec ( xUlpDbl / 2. ) ) ; return resul . round ( mc ) ; } else { /* Compute exp ( x ) = ( exp ( 0.1 * x ) ) ^ 10 . Division by 10 does not lead
 * to loss of accuracy . */
int exSc = ( int ) ( 1.0 - Math . log10 ( TAYLOR_NTERM * ( TAYLOR_NTERM - 1.0 ) * ( TAYLOR_NTERM - 2.0 ) * xUlpDbl / Math . pow ( xDbl , TAYLOR_NTERM ) ) / ( TAYLOR_NTERM - 1.0 ) ) ; BigDecimal xby10 = x . scaleByPowerOfTen ( - exSc ) ; BigDecimal expxby10 = exp ( xby10 ) ; /* Final powering by 10 means that the relative error of the result
 * is 10 times the relative error of the base ( First order binomial expansion ) .
 * This looses one digit . */
MathContext mc = new MathContext ( expxby10 . precision ( ) - exSc ) ; /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation
 17
 * response by the BigDecimal . pow library or integer overflow . */
while ( exSc > 0 ) { int exsub = Math . min ( 8 , exSc ) ; exSc -= exsub ; MathContext mctmp = new MathContext ( expxby10 . precision ( ) - exsub + 2 ) ; int pex = 1 ; while ( exsub -- > 0 ) { pex *= 10 ; } expxby10 = expxby10 . pow ( pex , mctmp ) ; } return expxby10 . round ( mc ) ; } }


signature:
public class BigDecimalMath { /** * The base of the natural logarithm .
 * @ param mc the required precision of the result
 * @ return exp ( 1 ) = 2.71828 . . . . */
static public BigDecimal exp ( final MathContext mc ) { } }

implementation:
/* look it up if possible */
if ( mc . getPrecision ( ) < E . precision ( ) ) { return E . round ( mc ) ; } else { /* Instantiate a 1.0 with the requested pseudo - accuracy
 * and delegate the computation to the public method above . */
BigDecimal uni = scalePrec ( BigDecimal . ONE , mc . getPrecision ( ) ) ; return exp ( uni ) ; }


signature:
public class BigDecimalMath { /** * The natural logarithm .
 * @ param x the argument .
 * @ return ln ( x ) .
 * The precision of the result is implicitly defined by the precision in the argument . */
static public BigDecimal log ( BigDecimal x ) { } }

implementation:
/* the value is undefined if x is negative . */
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( "Cannot take log of negative " + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { /* log 1 . = 0. */
return scalePrec ( BigDecimal . ZERO , x . precision ( ) - 1 ) ; } else if ( Math . abs ( x . doubleValue ( ) - 1.0 ) <= 0.3 ) { /* The standard Taylor series around x = 1 , z = 0 , z = x - 1 . Abramowitz - Stegun 4.124.
 * The absolute error is err ( z ) / ( 1 + z ) = err ( x ) / x . */
BigDecimal z = scalePrec ( x . subtract ( BigDecimal . ONE ) , 2 ) ; BigDecimal zpown = z ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . abs ( x . doubleValue ( ) ) ; BigDecimal resul = z ; for ( int k = 2 ; ; k ++ ) { zpown = multiplyRound ( zpown , z ) ; BigDecimal c = divideRound ( zpown , k ) ; if ( k % 2 == 0 ) { resul = resul . subtract ( c ) ; } else { resul = resul . add ( c ) ; } if ( Math . abs ( c . doubleValue ( ) ) < eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else { final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; /* Map log ( x ) = log root [ r ] ( x ) ^ r = r * log ( root [ r ] ( x ) ) with the aim
 * to move roor [ r ] ( x ) near to 1.2 ( that is , below the 0.3 appearing above ) , where log ( 1.2 ) is roughly 0.2. */
int r = ( int ) ( Math . log ( xDbl ) / 0.2 ) ; /* Since the actual requirement is a function of the value 0.3 appearing above ,
 * we avoid the hypothetical case of endless recurrence by ensuring that r > = 2. */
r = Math . max ( 2 , r ) ; /* Compute r - th root with 2 additional digits of precision */
BigDecimal xhighpr = scalePrec ( x , 2 ) ; BigDecimal resul = root ( r , xhighpr ) ; resul = log ( resul ) . multiply ( new BigDecimal ( r ) ) ; /* error propagation : log ( x + errx ) = log ( x ) + errx / x , so the absolute error
 * in the result equals the relative error in the input , xUlpDbl / xDbl . */
MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , xUlpDbl / xDbl ) ) ; return resul . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The natural logarithm .
 * @ param n The main argument , a strictly positive integer .
 * @ param mc The requirements on the precision .
 * @ return ln ( n ) . */
static public BigDecimal log ( int n , final MathContext mc ) { } }

implementation:
/* the value is undefined if x is negative . */
if ( n <= 0 ) { throw new ArithmeticException ( "Cannot take log of negative " + n ) ; } else if ( n == 1 ) { return BigDecimal . ZERO ; } else if ( n == 2 ) { if ( mc . getPrecision ( ) < LOG2 . precision ( ) ) { return LOG2 . round ( mc ) ; } else { /* Broadhurst \ protect \ vrule width0pt \ protect \ href { http : / / arxiv . org / abs / math / 9803067 } { arXiv : math / 9803067}
 * Error propagation : the error in log ( 2 ) is twice the error in S ( 2 , - 5 , . . . ) . */
int [ ] a = { 2 , - 5 , - 2 , - 7 , - 2 , - 5 , 2 , - 3 } ; BigDecimal S = broadhurstBBP ( 2 , 1 , a , new MathContext ( 1 + mc . getPrecision ( ) ) ) ; S = S . multiply ( new BigDecimal ( 8 ) ) ; S = sqrt ( divideRound ( S , 3 ) ) ; return S . round ( mc ) ; } } else if ( n == 3 ) { /* summation of a series roughly proportional to ( 7/500 ) ^ k . Estimate count
 * of terms to estimate the precision ( drop the favorable additional
 * 1 / k here ) : 0.013 ^ k < = 10 ^ ( - precision ) , so k * log10(0.013 ) < = - precision
 * so k > = precision / 1.87. */
int kmax = ( int ) ( mc . getPrecision ( ) / 1.87 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 0.693 / 1.098 ) ) ) ; BigDecimal log3 = multiplyRound ( log ( 2 , mcloc ) , 19 ) ; /* log3 is roughly 1 , so absolute and relative error are the same . The
 * result will be divided by 12 , so a conservative error is the one
 * already found in mc */
double eps = prec2err ( 1.098 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 7153 , 524288 ) ; Rational pk = new Rational ( 7153 , 524288 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum ? */
mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; if ( k % 2 != 0 ) { log3 = log3 . add ( c ) ; } else { log3 = log3 . subtract ( c ) ; } pk = pk . multiply ( r ) ; } log3 = divideRound ( log3 , 12 ) ; return log3 . round ( mc ) ; } else if ( n == 5 ) { /* summation of a series roughly proportional to ( 7/160 ) ^ k . Estimate count
 * of terms to estimate the precision ( drop the favorable additional
 * 1 / k here ) : 0.046 ^ k < = 10 ^ ( - precision ) , so k * log10(0.046 ) < = - precision
 * so k > = precision / 1.33. */
int kmax = ( int ) ( mc . getPrecision ( ) / 1.33 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 0.693 / 1.609 ) ) ) ; BigDecimal log5 = multiplyRound ( log ( 2 , mcloc ) , 14 ) ; /* log5 is roughly 1.6 , so absolute and relative error are the same . The
 * result will be divided by 6 , so a conservative error is the one
 * already found in mc */
double eps = prec2err ( 1.6 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 759 , 16384 ) ; Rational pk = new Rational ( 759 , 16384 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum ? */
mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; log5 = log5 . subtract ( c ) ; pk = pk . multiply ( r ) ; } log5 = divideRound ( log5 , 6 ) ; return log5 . round ( mc ) ; } else if ( n == 7 ) { /* summation of a series roughly proportional to ( 1/8 ) ^ k . Estimate count
 * of terms to estimate the precision ( drop the favorable additional
 * 1 / k here ) : 0.125 ^ k < = 10 ^ ( - precision ) , so k * log10(0.125 ) < = - precision
 * so k > = precision / 0.903. */
int kmax = ( int ) ( mc . getPrecision ( ) / 0.903 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 3 * 0.693 / 1.098 ) ) ) ; BigDecimal log7 = multiplyRound ( log ( 2 , mcloc ) , 3 ) ; /* log7 is roughly 1.9 , so absolute and relative error are the same . */
double eps = prec2err ( 1.9 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 1 , 8 ) ; Rational pk = new Rational ( 1 , 8 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum ? */
mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; log7 = log7 . subtract ( c ) ; pk = pk . multiply ( r ) ; } return log7 . round ( mc ) ; } else { /* At this point one could either forward to the log ( BigDecimal ) signature ( implemented )
 * or decompose n into Ifactors and use an implemenation of all the prime bases .
 * Estimate of the result ; convert the mc argument to an absolute error eps
 * log ( n + errn ) = log ( n ) + errn / n = log ( n ) + eps */
double res = Math . log ( ( double ) n ) ; double eps = prec2err ( res , mc . getPrecision ( ) ) ; /* errn = eps * n , convert absolute error in result to requirement on absolute error in input */
eps *= n ; /* Convert this absolute requirement of error in n to a relative error in n */
final MathContext mcloc = new MathContext ( 1 + err2prec ( ( double ) n , eps ) ) ; /* Padd n with a number of zeros to trigger the required accuracy in
 * the standard signature method */
BigDecimal nb = scalePrec ( new BigDecimal ( n ) , mcloc ) ; return log ( nb ) ; }


signature:
public class BigDecimalMath { /** * The natural logarithm .
 * @ param r The main argument , a strictly positive value .
 * @ param mc The requirements on the precision .
 * @ return ln ( r ) . */
static public BigDecimal log ( final Rational r , final MathContext mc ) { } }

implementation:
/* the value is undefined if x is negative . */
if ( r . compareTo ( Rational . ZERO ) <= 0 ) { throw new ArithmeticException ( "Cannot take log of negative " + r . toString ( ) ) ; } else if ( r . compareTo ( Rational . ONE ) == 0 ) { return BigDecimal . ZERO ; } else { /* log ( r + epsr ) = log ( r ) + epsr / r . Convert the precision to an absolute error in the result .
 * eps contains the required absolute error of the result , epsr / r . */
double eps = prec2err ( Math . log ( r . doubleValue ( ) ) , mc . getPrecision ( ) ) ; /* Convert this further into a requirement of the relative precision in r , given that
 * epsr / r is also the relative precision of r . Add one safety digit . */
MathContext mcloc = new MathContext ( 1 + err2prec ( eps ) ) ; final BigDecimal resul = log ( r . BigDecimalValue ( mcloc ) ) ; return resul . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * Power function .
 * @ param x Base of the power .
 * @ param y Exponent of the power .
 * @ return x ^ y .
 * The estimation of the relative error in the result is | log ( x ) * err ( y ) | + | y * err ( x ) / x | */
static public BigDecimal pow ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( "Cannot power negative " + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* return x ^ y = exp ( y * log ( x ) ) ; */
BigDecimal logx = log ( x ) ; BigDecimal ylogx = y . multiply ( logx ) ; BigDecimal resul = exp ( ylogx ) ; /* The estimation of the relative error in the result is | log ( x ) * err ( y ) | + | y * err ( x ) / x | */
double errR = Math . abs ( logx . doubleValue ( ) * y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( y . doubleValue ( ) * x . ulp ( ) . doubleValue ( ) / 2. / x . doubleValue ( ) ) ; MathContext mcR = new MathContext ( err2prec ( 1.0 , errR ) ) ; return resul . round ( mcR ) ; }


signature:
public class BigDecimalMath { /** * Raise to an integer power and round .
 * @ param x The base .
 * @ param n The exponent .
 * @ return x ^ n . */
static public BigDecimal powRound ( final BigDecimal x , final int n ) { } }

implementation:
/* The relative error in the result is n times the relative error in the input .
 * The estimation is slightly optimistic due to the integer rounding of the logarithm . */
MathContext mc = new MathContext ( x . precision ( ) - ( int ) Math . log10 ( ( double ) ( Math . abs ( n ) ) ) ) ; return x . pow ( n , mc ) ;


signature:
public class BigDecimalMath { /** * Trigonometric sine .
 * @ param x The argument in radians .
 * @ return sin ( x ) in the range - 1 to 1. */
static public BigDecimal sin ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return sin ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* reduce modulo 2pi */
BigDecimal res = mod2pi ( x ) ; double errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; int val = 2 + err2prec ( FastMath . PI , errpi ) ; MathContext mc = new MathContext ( val ) ; BigDecimal p = pi ( mc ) ; mc = new MathContext ( x . precision ( ) ) ; if ( res . compareTo ( p ) > 0 ) { /* pi < x < = 2pi : sin ( x ) = - sin ( x - pi ) */
return sin ( subtractRound ( res , p ) ) . negate ( ) ; } else if ( res . multiply ( new BigDecimal ( 2 ) ) . compareTo ( p ) > 0 ) { /* pi / 2 < x < = pi : sin ( x ) = sin ( pi - x ) */
return sin ( subtractRound ( p , res ) ) ; } else { /* for the range 0 < = x < Pi / 2 one could use sin ( 2x ) = 2sin ( x ) cos ( x )
 * to split this further . Here , use the sine up to pi / 4 and the cosine higher up . */
if ( res . multiply ( new BigDecimal ( 4 ) ) . compareTo ( p ) > 0 ) { /* x > pi / 4 : sin ( x ) = cos ( pi / 2 - x ) */
return cos ( subtractRound ( p . divide ( new BigDecimal ( 2 ) ) , res ) ) ; } else { /* Simple Taylor expansion , sum _ { i = 1 . . infinity } ( - 1 ) ^ ( . . ) res ^ ( 2i + 1 ) / ( 2i + 1 ) ! */
BigDecimal resul = res ; /* x ^ i */
BigDecimal xpowi = res ; /* 2i + 1 factorial */
BigInteger ifac = BigInteger . ONE ; /* The error in the result is set by the error in x itself . */
double xUlpDbl = res . 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 ) ( res . precision ( ) / Math . log10 ( 1.0 / res . doubleValue ( ) ) ) / 2 ; MathContext mcTay = new MathContext ( err2prec ( res . doubleValue ( ) , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD : at which precision will 2 * i or 2 * i + 1 overflow ? */
ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ; xpowi = xpowi . multiply ( res ) . multiply ( res ) . negate ( ) ; 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 . */
mc = new MathContext ( res . precision ( ) ) ; return resul . round ( mc ) ; } } } /* sin */


signature:
public class BigDecimalMath { /** * The trigonometric tangent .
 * @ param x the argument in radians .
 * @ return the tan ( x ) */
static public BigDecimal tan ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return tan ( x . negate ( ) ) . negate ( ) ; } else { /* reduce modulo pi */
BigDecimal res = modpi ( x ) ; /* absolute error in the result is err ( x ) / cos ^ 2 ( x ) to lowest order */
final double xDbl = res . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . pow ( Math . cos ( xDbl ) , 2. ) ; if ( xDbl > 0.8 ) { /* tan ( x ) = 1 / cot ( x ) */
BigDecimal co = cot ( x ) ; MathContext mc = new MathContext ( err2prec ( 1. / co . doubleValue ( ) , eps ) ) ; return BigDecimal . ONE . divide ( co , mc ) ; } else { final BigDecimal xhighpr = scalePrec ( res , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) ; BigDecimal result = xhighpr . plus ( ) ; /* x ^ ( 2i + 1) */
BigDecimal xpowi = xhighpr ; Bernoulli b = new Bernoulli ( ) ; /* 2 ^ ( 2i ) */
BigInteger fourn = BigInteger . valueOf ( 4 ) ; /* (2i ) ! */
BigInteger fac = BigInteger . valueOf ( 2 ) ; for ( int i = 2 ; ; i ++ ) { Rational f = b . at ( 2 * i ) . abs ( ) ; fourn = fourn . shiftLeft ( 2 ) ; fac = fac . multiply ( BigInteger . valueOf ( 2 * i ) ) . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; f = f . multiply ( fourn ) . multiply ( fourn . subtract ( BigInteger . ONE ) ) . divide ( fac ) ; xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = multiplyRound ( xpowi , f ) ; result = result . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( result . doubleValue ( ) , eps ) ) ; return result . round ( mc ) ; } }


signature:
public class BigDecimalMath { /** * The inverse trigonometric sine .
 * @ param x the argument .
 * @ return the arcsin ( x ) in radians . */
static public BigDecimal asin ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ONE ) > 0 || x . compareTo ( BigDecimal . ONE . negate ( ) ) < 0 ) { throw new ArithmeticException ( "Out of range argument " + x . toString ( ) + " of asin" ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { /* arcsin ( 1 ) = pi / 2 */
double errpi = Math . sqrt ( x . ulp ( ) . doubleValue ( ) ) ; MathContext mc = new MathContext ( err2prec ( 3.14159 , errpi ) ) ; return pi ( mc ) . divide ( new BigDecimal ( 2 ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return asin ( x . negate ( ) ) . negate ( ) ; } else if ( x . doubleValue ( ) > 0.7 ) { final BigDecimal xCompl = BigDecimal . ONE . subtract ( x ) ; final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . sqrt ( 1. - Math . pow ( xDbl , 2. ) ) ; final BigDecimal xhighpr = scalePrec ( xCompl , 3 ) ; final BigDecimal xhighprV = divideRound ( xhighpr , 4 ) ; BigDecimal resul = BigDecimal . ONE ; /* x ^ ( 2i + 1) */
BigDecimal xpowi = BigDecimal . ONE ; /* i factorial */
BigInteger ifacN = BigInteger . ONE ; BigInteger ifacD = BigInteger . ONE ; for ( int i = 1 ; ; i ++ ) { ifacN = ifacN . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifacD = ifacD . multiply ( BigInteger . valueOf ( i ) ) ; if ( i == 1 ) { xpowi = xhighprV ; } else { xpowi = multiplyRound ( xpowi , xhighprV ) ; } BigDecimal c = divideRound ( multiplyRound ( xpowi , ifacN ) , ifacD . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ) ; resul = resul . add ( c ) ; /* series started 1 + x / 12 + . . . which yields an estimate of the sum ’ s error */
if ( Math . abs ( c . doubleValue ( ) ) < xUlpDbl / 120. ) { break ; } } /* sqrt ( 2 * z ) * ( 1 + . . . ) */
xpowi = sqrt ( xhighpr . multiply ( new BigDecimal ( 2 ) ) ) ; resul = multiplyRound ( xpowi , resul ) ; MathContext mc = new MathContext ( resul . precision ( ) ) ; BigDecimal pihalf = pi ( mc ) . divide ( new BigDecimal ( 2 ) ) ; mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return pihalf . subtract ( resul , mc ) ; } else { /* absolute error in the result is err ( x ) / sqrt ( 1 - x ^ 2 ) to lowest order */
final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . sqrt ( 1. - Math . pow ( xDbl , 2. ) ) ; final BigDecimal xhighpr = scalePrec ( x , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) ; BigDecimal resul = xhighpr . plus ( ) ; /* x ^ ( 2i + 1) */
BigDecimal xpowi = xhighpr ; /* i factorial */
BigInteger ifacN = BigInteger . ONE ; BigInteger ifacD = BigInteger . ONE ; for ( int i = 1 ; ; i ++ ) { ifacN = ifacN . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifacD = ifacD . multiply ( BigInteger . valueOf ( 2 * i ) ) ; xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = divideRound ( multiplyRound ( xpowi , ifacN ) , ifacD . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The inverse trigonometric tangent .
 * @ param x the argument .
 * @ return the principal value of arctan ( x ) in radians in the range - pi / 2 to + pi / 2. */
static public BigDecimal atan ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return atan ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . doubleValue ( ) > 0.7 && x . doubleValue ( ) < 3.0 ) { /* Abramowitz - Stegun 4.4.34 convergence acceleration
 * 2 * arctan ( x ) = arctan ( 2x / ( 1 - x ^ 2 ) ) = arctan ( y ) . x = ( sqrt ( 1 + y ^ 2 ) - 1 ) / y
 * This maps 0 < = y < = 3 to 0 < = x < = 0.73 roughly . Temporarily with 2 protectionist digits . */
BigDecimal y = scalePrec ( x , 2 ) ; BigDecimal newx = divideRound ( hypot ( 1 , y ) . subtract ( BigDecimal . ONE ) , y ) ; /* intermediate result with too optimistic error estimate */
BigDecimal resul = multiplyRound ( atan ( newx ) , 2 ) ; /* absolute error in the result is errx / ( 1 + x ^ 2 ) , where errx = half of the ulp . */
double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else if ( x . doubleValue ( ) < 0.71 ) { /* Taylor expansion around x = 0 ; Abramowitz - Stegun 4.4.42 */
final BigDecimal xhighpr = scalePrec ( x , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) . negate ( ) ; BigDecimal resul = xhighpr . plus ( ) ; /* signed x ^ ( 2i + 1) */
BigDecimal xpowi = xhighpr ; /* absolute error in the result is errx / ( 1 + x ^ 2 ) , where errx = half of the ulp . */
double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; for ( int i = 1 ; ; i ++ ) { xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = divideRound ( xpowi , 2 * i + 1 ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else { /* Taylor expansion around x = infinity ; Abramowitz - Stegun 4.4.42 */
/* absolute error in the result is errx / ( 1 + x ^ 2 ) , where errx = half of the ulp . */
double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; /* start with the term pi / 2 ; gather its precision relative to the expected result */
MathContext mc = new MathContext ( 2 + err2prec ( 3.1416 , eps ) ) ; BigDecimal onepi = pi ( mc ) ; BigDecimal resul = onepi . divide ( new BigDecimal ( 2 ) ) ; final BigDecimal xhighpr = divideRound ( - 1 , scalePrec ( x , 2 ) ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) . negate ( ) ; /* signed x ^ ( 2i + 1) */
BigDecimal xpowi = xhighpr ; for ( int i = 0 ; ; i ++ ) { BigDecimal c = divideRound ( xpowi , 2 * i + 1 ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } xpowi = multiplyRound ( xpowi , xhighprSq ) ; } mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The hyperbolic cosine .
 * @ param x The argument .
 * @ return The cosh ( x ) = ( exp ( x ) + exp ( - x ) ) / 2 . */
static public BigDecimal cosh ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return cos ( x . negate ( ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ONE ; } else { if ( x . doubleValue ( ) > 1.5 ) { /* cosh ^ 2 ( x ) = 1 + sinh ^ 2 ( x ) . */
return hypot ( 1 , sinh ( x ) ) ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* Simple Taylor expansion , sum _ { 0 = 1 . . infinity } x ^ ( 2i ) / ( 2i ) ! */
BigDecimal resul = BigDecimal . ONE ; /* x ^ i */
BigDecimal xpowi = BigDecimal . ONE ; /* 2i factorial */
BigInteger ifac = BigInteger . ONE ; /* The absolute error in the result is the error in x ^ 2/2 which is x times the error in x . */
double xUlpDbl = 0.5 * x . ulp ( ) . doubleValue ( ) * x . doubleValue ( ) ; /* The error in the result is set by the error in x ^ 2/2 itself , xUlpDbl .
 * We need at most k terms to push x ^ ( 2k ) / ( 2k ) ! below this value .
 * x ^ ( 2k ) < xUlpDbl ; ( 2k ) * log ( x ) < log ( xUlpDbl ) ; */
int k = ( int ) ( Math . log ( xUlpDbl ) / Math . log ( x . doubleValue ( ) ) ) / 2 ; /* The individual terms are all smaller than 1 , so an estimate of 1.0 for
 * the absolute value will give a safe relative error estimate for the indivdual terms */
MathContext mcTay = new MathContext ( err2prec ( 1. , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD : at which precision will 2 * i - 1 or 2 * i overflow ? */
ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i ) ) ; 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 governed by the error in x itself . */
MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , xUlpDbl ) ) ; return resul . round ( mc ) ; } }


signature:
public class BigDecimalMath { /** * The hyperbolic sine .
 * @ param x the argument .
 * @ return the sinh ( x ) = ( exp ( x ) - exp ( - x ) ) / 2 . */
static public BigDecimal sinh ( final BigDecimal x ) { } }

implementation:
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 ( BigInteger . valueOf ( 2 * i ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 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 ) ; } }


signature:
public class BigDecimalMath { /** * The hyperbolic tangent .
 * @ param x The argument .
 * @ return The tanh ( x ) = sinh ( x ) / cosh ( x ) . */
static public BigDecimal tanh ( final BigDecimal x ) { } }

implementation:
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 ) ; }


signature:
public class BigDecimalMath { /** * The inverse hyperbolic sine .
 * @ param x The argument .
 * @ return The arcsinh ( x ) . */
static public BigDecimal asinh ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* arcsinh ( x ) = log ( x + hypot ( 1 , x ) ) */
BigDecimal logx = log ( hypot ( 1 , xhighpr ) . add ( xhighpr ) ) ; /* The absolute error in arcsinh x is err ( x ) / sqrt ( 1 + x ^ 2) */
double xDbl = x . doubleValue ( ) ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . hypot ( 1. , xDbl ) ; MathContext mc = new MathContext ( err2prec ( logx . doubleValue ( ) , eps ) ) ; return logx . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The inverse hyperbolic cosine .
 * @ param x The argument .
 * @ return The arccosh ( x ) . */
static public BigDecimal acosh ( final BigDecimal x ) { } }

implementation:
if ( x . compareTo ( BigDecimal . ONE ) < 0 ) { throw new ArithmeticException ( "Out of range argument cosh " + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* arccosh ( x ) = log ( x + sqrt ( x ^ 2-1 ) ) */
BigDecimal logx = log ( sqrt ( xhighpr . pow ( 2 ) . subtract ( BigDecimal . ONE ) ) . add ( xhighpr ) ) ; /* The absolute error in arcsinh x is err ( x ) / sqrt ( x ^ 2-1) */
double xDbl = x . doubleValue ( ) ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . sqrt ( xDbl * xDbl - 1. ) ; MathContext mc = new MathContext ( err2prec ( logx . doubleValue ( ) , eps ) ) ; return logx . round ( mc ) ; }


signature:
public class BigDecimalMath { /** * The Gamma function .
 * @ param x The argument .
 * @ return Gamma ( x ) . */
static public BigDecimal Gamma ( final BigDecimal x ) { } }

implementation:
/* reduce to interval near 1.0 with the functional relation , Abramowitz - Stegun 6.1.33 */
if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return divideRound ( Gamma ( x . add ( BigDecimal . ONE ) ) , x ) ; } else if ( x . doubleValue ( ) > 1.5 ) { /* Gamma ( x ) = Gamma ( xmin + n ) = Gamma ( xmin ) * Pochhammer ( xmin , n ) . */
int n = ( int ) ( x . doubleValue ( ) - 0.5 ) ; BigDecimal xmin1 = x . subtract ( new BigDecimal ( n ) ) ; return multiplyRound ( Gamma ( xmin1 ) , pochhammer ( xmin1 , n ) ) ; } else { /* apply Abramowitz - Stegun 6.1.33 */
BigDecimal z = x . subtract ( BigDecimal . ONE ) ; /* add intermediately 2 digits to the partial sum accumulation */
z = scalePrec ( z , 2 ) ; MathContext mcloc = new MathContext ( z . precision ( ) ) ; /* measure of the absolute error is the relative error in the first , logarithmic term */
double eps = x . ulp ( ) . doubleValue ( ) / x . doubleValue ( ) ; BigDecimal resul = log ( scalePrec ( x , 2 ) ) . negate ( ) ; if ( x . compareTo ( BigDecimal . ONE ) != 0 ) { BigDecimal gammCompl = BigDecimal . ONE . subtract ( gamma ( mcloc ) ) ; resul = resul . add ( multiplyRound ( z , gammCompl ) ) ; for ( int n = 2 ; ; n ++ ) { /* multiplying z ^ n / n by zeta ( n - 1 ) means that the two relative errors add .
 * so the requirement in the relative error of zeta ( n ) - 1 is that this is somewhat
 * smaller than the relative error in z ^ n / n ( the absolute error of thelatter is the
 * absolute error in z ) */
BigDecimal c = divideRound ( z . pow ( n , mcloc ) , n ) ; MathContext m = new MathContext ( err2prec ( n * z . ulp ( ) . doubleValue ( ) / 2. / z . doubleValue ( ) ) ) ; c = c . round ( m ) ; /* At larger n , zeta ( n ) - 1 is roughly 1/2 ^ n . The product is c / 2 ^ n .
 * The relative error in c is c . ulp / 2 / c . The error in the product should be small versus eps / 10.
 * Error from 1/2 ^ n is c * err ( sigma - 1 ) .
 * We need a relative error of zeta - 1 of the order of c . ulp / 50 / c . This is an absolute
 * error in zeta - 1 of c . ulp / 50 / c / 2 ^ n , and also the absolute error in zeta , because zeta is
 * of the order of 1. */
if ( eps / 100. / c . doubleValue ( ) < 0.01 ) { m = new MathContext ( err2prec ( eps / 100. / c . doubleValue ( ) ) ) ; } else { m = new MathContext ( 2 ) ; } /* zeta ( n ) - 1 */
BigDecimal zetm1 = zeta ( n , m ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , zetm1 ) ; if ( n % 2 == 0 ) { resul = resul . add ( c ) ; } else { resul = resul . subtract ( c ) ; } /* alternating sum , so truncating as eps is reached suffices */
if ( Math . abs ( c . doubleValue ( ) ) < eps ) { break ; } } } /* The relative error in the result is the absolute error in the
 * input variable times the digamma ( psi ) value at that point . */
double psi = 0.5772156649 ; double zdbl = z . doubleValue ( ) ; for ( int n = 1 ; n < 5 ; n ++ ) { psi += zdbl / n / ( n + zdbl ) ; } eps = psi * x . ulp ( ) . doubleValue ( ) / 2. ; mcloc = new MathContext ( err2prec ( eps ) ) ; return exp ( resul ) . round ( mcloc ) ; }


signature:
public class BigDecimalMath { /** * Pochhammer ’ s function .
 * @ param x The main argument .
 * @ param n The non - negative index .
 * @ return ( x ) _ n = x ( x + 1 ) ( x + 2 ) * . . . * ( x + n - 1 ) . */
static public BigDecimal pochhammer ( final BigDecimal x , final int n ) { } }

implementation:
/* reduce to interval near 1.0 with the functional relation , Abramowitz - Stegun 6.1.33 */
if ( n < 0 ) { throw new ProviderException ( "Unimplemented pochhammer with negative index " + n ) ; } else if ( n == 0 ) { return BigDecimal . ONE ; } else { /* internally two safety digits */
BigDecimal xhighpr = scalePrec ( x , 2 ) ; BigDecimal resul = xhighpr ; double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; double xDbl = x . doubleValue ( ) ; /* relative error of the result is the sum of the relative errors of the factors */
double eps = 0.5 * xUlpDbl / Math . abs ( xDbl ) ; for ( int i = 1 ; i < n ; i ++ ) { eps += 0.5 * xUlpDbl / Math . abs ( xDbl + i ) ; resul = resul . multiply ( xhighpr . add ( new BigDecimal ( i ) ) ) ; final MathContext mcloc = new MathContext ( 4 + err2prec ( eps ) ) ; resul = resul . round ( mcloc ) ; } return resul . round ( new MathContext ( err2prec ( eps ) ) ) ; }


signature:
public class BigDecimalMath { /** * Reduce value to the interval [ 0,2 * Pi ] .
 * @ param x the original value
 * @ return the value modulo 2 * pi in the interval from 0 to 2 * pi . */
static public BigDecimal mod2pi ( BigDecimal x ) { } }

implementation:
/* write x = 2 * pi * k + r with the precision in r defined by the precision of x and not
 * compromised by the precision of 2 * pi , so the ulp of 2 * pi * k should match the ulp of x .
 * First getFloat a guess of k to figure out how many digits of 2 * pi are needed . */
int k = ( int ) ( 0.5 * x . doubleValue ( ) / Math . PI ) ; /* want to have err ( 2 * pi * k ) < err ( x ) = 0.5 * x . ulp , so err ( pi ) = err ( x ) / ( 4k ) with two safety digits */
double err2pi ; if ( k != 0 ) { err2pi = 0.25 * Math . abs ( x . ulp ( ) . doubleValue ( ) / k ) ; } else { err2pi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; } MathContext mc = new MathContext ( 2 + err2prec ( 6.283 , err2pi ) ) ; BigDecimal twopi = pi ( mc ) . multiply ( new BigDecimal ( 2 ) ) ; /* Delegate the actual operation to the BigDecimal class , which may return
 * a negative value of x was negative . */
BigDecimal res = x . remainder ( twopi ) ; if ( res . compareTo ( BigDecimal . ZERO ) < 0 ) { res = res . add ( twopi ) ; } /* The actual precision is set by the input value , its absolute value of x . ulp ( ) / 2. */
mc = new MathContext ( err2prec ( res . doubleValue ( ) , x . ulp ( ) . doubleValue ( ) / 2. ) ) ; return res . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Reduce value to the interval [ - Pi / 2 , Pi / 2 ] .
 * @ param x The original value
 * @ return The value modulo pi , shifted to the interval from - Pi / 2 to Pi / 2. */
static public BigDecimal modpi ( BigDecimal x ) { } }

implementation:
/* write x = pi * k + r with the precision in r defined by the precision of x and not
 * compromised by the precision of pi , so the ulp of pi * k should match the ulp of x .
 * First getFloat a guess of k to figure out how many digits of pi are needed . */
int k = ( int ) ( x . doubleValue ( ) / Math . PI ) ; /* want to have err ( pi * k ) < err ( x ) = x . ulp / 2 , so err ( pi ) = err ( x ) / ( 2k ) with two safety digits */
double errpi ; if ( k != 0 ) { errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) / k ) ; } else { errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; } MathContext mc = new MathContext ( 2 + err2prec ( 3.1416 , errpi ) ) ; BigDecimal onepi = pi ( mc ) ; BigDecimal pihalf = onepi . divide ( new BigDecimal ( 2 ) ) ; /* Delegate the actual operation to the BigDecimal class , which may return
 * a negative value of x was negative . */
BigDecimal res = x . remainder ( onepi ) ; if ( res . compareTo ( pihalf ) > 0 ) { res = res . subtract ( onepi ) ; } else if ( res . compareTo ( pihalf . negate ( ) ) < 0 ) { res = res . add ( onepi ) ; } /* The actual precision is set by the input value , its absolute value of x . ulp ( ) / 2. */
mc = new MathContext ( err2prec ( res . doubleValue ( ) , x . ulp ( ) . doubleValue ( ) / 2. ) ) ; return res . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Riemann zeta function .
 * @ param n The positive integer argument .
 * 32
 * @ param mc Specification of the accuracy of the result .
 * @ return zeta ( n ) . */
static public BigDecimal zeta ( final int n , final MathContext mc ) { } }

implementation:
if ( n <= 0 ) { throw new ProviderException ( "Unimplemented zeta at negative argument " + n ) ; } if ( n == 1 ) { throw new ArithmeticException ( "Pole at zeta(1) " ) ; } if ( n % 2 == 0 ) { /* Even indices . Abramowitz - Stegun 23.2.16 . Start with 2 ^ ( n - 1 ) * B ( n ) / n ! */
Rational b = ( new Bernoulli ( ) ) . at ( n ) . abs ( ) ; b = b . divide ( ( new Factorial ( ) ) . at ( n ) ) ; b = b . multiply ( BigInteger . ONE . shiftLeft ( n - 1 ) ) ; /* to be multiplied by pi ^ n . Absolute error in the result of pi ^ n is n times
 * error in pi times pi ^ ( n - 1 ) . Relative error is n * error ( pi ) / pi , requested by mc .
 * Need one more digit in pi if n = 10 , two digits if n = 100 etc , and add one extra digit . */
MathContext mcpi = new MathContext ( mc . getPrecision ( ) + ( int ) ( Math . log10 ( 10.0 * n ) ) ) ; final BigDecimal piton = pi ( mcpi ) . pow ( n , mc ) ; return multiplyRound ( piton , b ) ; } else if ( n == 3 ) { /* Broadhurst BBP \ protect \ vrule width0pt \ protect \ href { http : / / arxiv . org / abs / math / 9803067 } { arXiv : math / 9803067}
 * Error propagation : S31 is roughly 0.087 , S33 roughly 0.131 */
int [ ] a31 = { 1 , - 7 , - 1 , 10 , - 1 , - 7 , 1 , 0 } ; int [ ] a33 = { 1 , 1 , - 1 , - 2 , - 1 , 1 , 1 , 0 } ; BigDecimal S31 = broadhurstBBP ( 3 , 1 , a31 , mc ) ; BigDecimal S33 = broadhurstBBP ( 3 , 3 , a33 , mc ) ; S31 = S31 . multiply ( new BigDecimal ( 48 ) ) ; S33 = S33 . multiply ( new BigDecimal ( 32 ) ) ; return S31 . add ( S33 ) . divide ( new BigDecimal ( 7 ) , mc ) ; } else if ( n == 5 ) { /* Broadhurst BBP \ protect \ vrule width0pt \ protect \ href { http : / / arxiv . org / abs / math / 9803067 } { arXiv : math / 9803067}
 * Error propagation : S51 is roughly - 11.15 , S53 roughly 22.165 , S55 is roughly 0.031
 * 9*2048 * S51/6265 = - 3.28 . 7*2038 * S53/61651 = 5.07 . 738*2048 * S55/61651 = 0.747.
 * The result is of the order 1.03 , so we add 2 digits to S51 and S52 and one digit to S55. */
int [ ] a51 = { 31 , - 1614 , - 31 , - 6212 , - 31 , - 1614 , 31 , 74552 } ; int [ ] a53 = { 173 , 284 , - 173 , - 457 , - 173 , 284 , 173 , - 111 } ; int [ ] a55 = { 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 } ; BigDecimal S51 = broadhurstBBP ( 5 , 1 , a51 , new MathContext ( 2 + mc . getPrecision ( ) ) ) ; BigDecimal S53 = broadhurstBBP ( 5 , 3 , a53 , new MathContext ( 2 + mc . getPrecision ( ) ) ) ; BigDecimal S55 = broadhurstBBP ( 5 , 5 , a55 , new MathContext ( 1 + mc . getPrecision ( ) ) ) ; S51 = S51 . multiply ( new BigDecimal ( 18432 ) ) ; S53 = S53 . multiply ( new BigDecimal ( 14336 ) ) ; S55 = S55 . multiply ( new BigDecimal ( 1511424 ) ) ; return S51 . add ( S53 ) . subtract ( S55 ) . divide ( new BigDecimal ( 62651 ) , mc ) ; } else { /* Cohen et al Exp Math 1 ( 1 ) ( 1992 ) 25 */
Rational betsum = new Rational ( ) ; Bernoulli bern = new Bernoulli ( ) ; Factorial fact = new Factorial ( ) ; for ( int npr = 0 ; npr <= ( n + 1 ) / 2 ; npr ++ ) { Rational b = bern . at ( 2 * npr ) . multiply ( bern . at ( n + 1 - 2 * npr ) ) ; b = b . divide ( fact . at ( 2 * npr ) ) . divide ( fact . at ( n + 1 - 2 * npr ) ) ; b = b . multiply ( 1 - 2 * npr ) ; if ( npr % 2 == 0 ) { betsum = betsum . add ( b ) ; } else { betsum = betsum . subtract ( b ) ; } } betsum = betsum . divide ( n - 1 ) ; /* The first term , including the facor ( 2pi ) ^ n , is essentially most
 * of the result , near one . The second term below is roughly in the range 0.003 to 0.009.
 * So the precision here is matching the precisionn requested by mc , and the precision
 * requested for 2 * pi is in absolute terms adjusted . */
MathContext mcloc = new MathContext ( 2 + mc . getPrecision ( ) + ( int ) ( Math . log10 ( ( double ) ( n ) ) ) ) ; BigDecimal ftrm = pi ( mcloc ) . multiply ( new BigDecimal ( 2 ) ) ; ftrm = ftrm . pow ( n ) ; ftrm = multiplyRound ( ftrm , betsum . BigDecimalValue ( mcloc ) ) ; BigDecimal exps = new BigDecimal ( 0 ) ; /* the basic accuracy of the accumulated terms before multiplication with 2 */
double eps = Math . pow ( 10. , - mc . getPrecision ( ) ) ; if ( n % 4 == 3 ) { /* since the argument n is at least 7 here , the drop
 * of the terms is at rather constant pace at least 10 ^ - 3 , for example
 * 0.0018 , 0.2e - 7 , 0.29e - 11 , 0.74e - 15 etc for npr = 1,2,3 . . . . We want 2 times these terms
 * fall below eps / 10. */
int kmax = mc . getPrecision ( ) / 3 ; eps /= kmax ; /* need an error of eps for 2 / ( exp ( 2pi ) - 1 ) = 0.0037
 * The absolute error is 4 * exp ( 2pi ) * err ( pi ) / ( exp ( 2pi ) - 1 ) ^ 2 = 0.0075 * err ( pi ) */
BigDecimal exp2p = pi ( new MathContext ( 3 + err2prec ( 3.14 , eps / 0.0075 ) ) ) ; exp2p = exp ( exp2p . multiply ( new BigDecimal ( 2 ) ) ) ; BigDecimal c = exp2p . subtract ( BigDecimal . ONE ) ; exps = divideRound ( 1 , c ) ; for ( int npr = 2 ; npr <= kmax ; npr ++ ) { /* the error estimate above for npr = 1 is the worst case of
 * the absolute error created by an error in 2pi . So we can
 * safely re - use the exp2p value computed above without
 * reassessment of its error . */
c = powRound ( exp2p , npr ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , ( BigInteger . valueOf ( npr ) ) . pow ( n ) ) ; c = divideRound ( 1 , c ) ; exps = exps . add ( c ) ; } } else { /* since the argument n is at least 9 here , the drop
 * of the terms is at rather constant pace at least 10 ^ - 3 , for example
 * 0.0096 , 0.5e - 7 , 0.3e - 11 , 0.6e - 15 etc . We want these terms
 * fall below eps / 10. */
int kmax = ( 1 + mc . getPrecision ( ) ) / 3 ; eps /= kmax ; /* need an error of eps for 2 / ( exp ( 2pi ) - 1 ) * ( 1 + 4 * Pi / 8 / ( 1 - exp ( - 2pi ) ) = 0.0096
 * at k = 7 or = 0.00766 at k = 13 for example .
 * The absolute error is 0.017 * err ( pi ) at k = 9 , 0.013 * err ( pi ) at k = 13 , 0.012 at k = 17 */
BigDecimal twop = pi ( new MathContext ( 3 + err2prec ( 3.14 , eps / 0.017 ) ) ) ; twop = twop . multiply ( new BigDecimal ( 2 ) ) ; BigDecimal exp2p = exp ( twop ) ; BigDecimal c = exp2p . subtract ( BigDecimal . ONE ) ; exps = divideRound ( 1 , c ) ; c = BigDecimal . ONE . subtract ( divideRound ( 1 , exp2p ) ) ; c = divideRound ( twop , c ) . multiply ( new BigDecimal ( 2 ) ) ; c = divideRound ( c , n - 1 ) . add ( BigDecimal . ONE ) ; exps = multiplyRound ( exps , c ) ; for ( int npr = 2 ; npr <= kmax ; npr ++ ) { c = powRound ( exp2p , npr ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , ( BigInteger . valueOf ( npr ) ) . pow ( n ) ) ; BigDecimal d = divideRound ( 1 , exp2p . pow ( npr ) ) ; d = BigDecimal . ONE . subtract ( d ) ; d = divideRound ( twop , d ) . multiply ( new BigDecimal ( 2 * npr ) ) ; d = divideRound ( d , n - 1 ) . add ( BigDecimal . ONE ) ; d = divideRound ( d , c ) ; exps = exps . add ( d ) ; } } exps = exps . multiply ( new BigDecimal ( 2 ) ) ; return ftrm . subtract ( exps , mc ) ; }


signature:
public class BigDecimalMath { /** * Riemann zeta function .
 * @ param n The positive integer argument .
 * @ return zeta ( n ) - 1. */
static public double zeta1 ( final int n ) { } }


signature:
public class BigDecimalMath { /** * Broadhurst ladder sequence .
 * @ param a The vector of 8 integer arguments
 * @ param mc Specification of the accuracy of the result
 * @ return S _ ( n , p ) ( a )
 * @ see \ protect \ vrule width0pt \ protect \ href { http : / / arxiv . org / abs / math / 9803067 } { arXiv : math / 9803067} */
static protected BigDecimal broadhurstBBP ( final int n , final int p , final int a [ ] , MathContext mc ) { } }

implementation:
/* Explore the actual magnitude of the result first with a quick estimate . */
double x = 0.0 ; for ( int k = 1 ; k < 10 ; k ++ ) { x += a [ ( k - 1 ) % 8 ] / Math . pow ( 2. , p * ( k + 1 ) / 2 ) / Math . pow ( ( double ) k , n ) ; } /* Convert the relative precision and estimate of the result into an absolute precision . */
double eps = prec2err ( x , mc . getPrecision ( ) ) ; /* Divide this through the number of terms in the sum to account for error accumulation
 * The divisor 2 ^ ( p ( k + 1 ) / 2 ) means that on the average each 8th term in k has shrunk by
 * relative to the 8th predecessor by 1/2 ^ ( 4p ) . 1/2 ^ ( 4pc ) = 10 ^ ( - precision ) with c the 8term
 * cycles yields c = log _ 2 ( 10 ^ precision ) / 4p = 3.3 * precision / 4p with k = 8c */
int kmax = ( int ) ( 6.6 * mc . getPrecision ( ) / p ) ; /* Now eps is the absolute error in each term */
eps /= kmax ; BigDecimal res = BigDecimal . ZERO ; for ( int c = 0 ; ; c ++ ) { Rational r = new Rational ( ) ; for ( int k = 0 ; k < 8 ; k ++ ) { Rational tmp = new Rational ( BigInteger . valueOf ( a [ k ] ) , BigInteger . valueOf ( ( 1 + 8 * c + k ) ) . pow ( n ) ) ; /* floor ( ( pk + p ) / 2) */
int pk1h = p * ( 2 + 8 * c + k ) / 2 ; tmp = tmp . divide ( BigInteger . ONE . shiftLeft ( pk1h ) ) ; r = r . add ( tmp ) ; } if ( Math . abs ( r . doubleValue ( ) ) < eps ) { break ; } MathContext mcloc = new MathContext ( 1 + err2prec ( r . doubleValue ( ) , eps ) ) ; res = res . add ( r . BigDecimalValue ( mcloc ) ) ; } return res . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Add and round according to the larger of the two ulp ’ s .
 * @ param x The left summand
 * @ param y The right summand
 * @ return The sum x + y . */
static public BigDecimal addRound ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
BigDecimal resul = x . add ( y ) ; /* The estimation of the absolute error in the result is | err ( y ) | + | err ( x ) | */
double errR = Math . abs ( y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( x . ulp ( ) . doubleValue ( ) / 2. ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , errR ) ) ; return resul . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Subtract and round according to the larger of the two ulp ’ s .
 * @ param x The left term .
 * @ param y The right term .
 * @ return The difference x - y . */
static public BigDecimal subtractRound ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
BigDecimal resul = x . subtract ( y ) ; /* The estimation of the absolute error in the result is | err ( y ) | + | err ( x ) | */
double errR = Math . abs ( y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( x . ulp ( ) . doubleValue ( ) / 2. ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , errR ) ) ; return resul . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Multiply and round .
 * @ param x The left factor .
 * @ param y The right factor .
 * @ return The product x * y . */
static public BigDecimal multiplyRound ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
BigDecimal resul = x . multiply ( y ) ; /* The estimation of the relative error in the result is the sum of the relative
 * errors | err ( y ) / y | + | err ( x ) / x | */
MathContext mc = new MathContext ( Math . min ( x . precision ( ) , y . precision ( ) ) ) ; return resul . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Multiply and round .
 * @ param x The left factor .
 * @ param f The right factor .
 * @ return The product x * f . */
static public BigDecimal multiplyRound ( final BigDecimal x , final Rational f ) { } }

implementation:
if ( f . compareTo ( BigInteger . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* Convert the rational value with two digits of extra precision */
MathContext mc = new MathContext ( 2 + x . precision ( ) ) ; BigDecimal fbd = f . BigDecimalValue ( mc ) ; /* and the precision of the product is then dominated by the precision in x */
return multiplyRound ( x , fbd ) ; }


signature:
public class BigDecimalMath { /** * Multiply and round .
 * @ param x The left factor .
 * @ param n The right factor .
 * @ return The product x * n . */
static public BigDecimal multiplyRound ( final BigDecimal x , final int n ) { } }

implementation:
BigDecimal resul = x . multiply ( new BigDecimal ( n ) ) ; /* The estimation of the absolute error in the result is | n * err ( x ) | */
MathContext mc = new MathContext ( n != 0 ? x . precision ( ) : 0 ) ; return resul . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Multiply and round .
 * @ param x The left factor .
 * @ param n The right factor .
 * @ return the product x * n */
static public BigDecimal multiplyRound ( final BigDecimal x , final BigInteger n ) { } }

implementation:
BigDecimal resul = x . multiply ( new BigDecimal ( n ) ) ; /* The estimation of the absolute error in the result is | n * err ( x ) | */
MathContext mc = new MathContext ( n . compareTo ( BigInteger . ZERO ) != 0 ? x . precision ( ) : 0 ) ; return resul . round ( mc ) ;


signature:
public class BigDecimalMath { /** * Divide and round .
 * @ param x The numerator
 * @ param y The denominator
 * @ return the divided x / y */
static public BigDecimal divideRound ( final BigDecimal x , final BigDecimal y ) { } }

implementation:
/* The estimation of the relative error in the result is | err ( y ) / y | + | err ( x ) / x | */
MathContext mc = new MathContext ( Math . min ( x . precision ( ) , y . precision ( ) ) ) ; return x . divide ( y , mc ) ;


signature:
public class BigDecimalMath { /** * Divide and round .
 * @ param n The numerator .
 * @ param x The denominator .
 * @ return the divided n / x . */
static public BigDecimal divideRound ( final int n , final BigDecimal x ) { } }

implementation:
/* The estimation of the relative error in the result is | err ( x ) / x | */
MathContext mc = new MathContext ( x . precision ( ) ) ; return new BigDecimal ( n ) . divide ( x , mc ) ;


signature:
public class BigDecimalMath { /** * Append decimal zeros to the value . This returns a value which appears to have
 * a higher precision than the input .
 * @ param x The input value
 * @ param d The ( positive ) value of zeros to be added as least significant digits .
 * @ return The same value as the input but with increased ( pseudo ) precision . */
static public BigDecimal scalePrec ( final BigDecimal x , int d ) { } }

implementation: return x . setScale ( d + x . scale ( ) ) ;


signature:
public class BigDecimalMath { /** * Boost the precision by appending decimal zeros to the value . This returns a value which appears to have
 * a higher precision than the input .
 * @ param x The input value
 * @ param mc The requirement on the minimum precision on return .
 * @ return The same value as the input but with increased ( pseudo ) precision . */
static public BigDecimal scalePrec ( final BigDecimal x , final MathContext mc ) { } }

implementation: final int diffPr = mc . getPrecision ( ) - x . precision ( ) ; if ( diffPr > 0 ) { return scalePrec ( x , diffPr ) ; } else { return x ; }


signature:
public class BigDecimalMath { /** * Convert an absolute error to a precision .
 * @ param x The value of the variable
 * @ param xerr The absolute error in the variable
 * @ return The number of valid digits in x .
 * The value is rounded down , and on the pessimistic side for that reason . */
static public int err2prec ( BigDecimal x , BigDecimal xerr ) { } }

implementation: return err2prec ( xerr . divide ( x , MathContext . DECIMAL64 ) . doubleValue ( ) ) ;


signature:
public class SameDiff { /** * Update the opName for the variable
 * with the given vertex id
 * @ param varName the vertex id to update
 * @ param withName thew new opName */
public void updateVariableName ( String varName , String withName ) { } }

implementation: SDVariable oldVarNameRef = getVariable ( varName ) ; variableMap . remove ( oldVarNameRef . getVarName ( ) ) ; val oldVarName = varName ; oldVarNameRef . setVarName ( withName ) ; variableMap . put ( withName , oldVarNameRef ) ; for ( val reverseValues : outgoingArgsReverse . entrySet ( ) ) { for ( int i = 0 ; i < reverseValues . getValue ( ) . length ; i ++ ) { if ( reverseValues . getValue ( ) [ i ] . equals ( oldVarName ) ) { reverseValues . getValue ( ) [ i ] = withName ; } } } for ( val reverseValues : incomingArgsReverse . entrySet ( ) ) { for ( int i = 0 ; i < reverseValues . getValue ( ) . length ; i ++ ) { if ( reverseValues . getValue ( ) [ i ] . equals ( oldVarName ) ) { reverseValues . getValue ( ) [ i ] = withName ; } } } if ( variableNameToArr . containsKey ( oldVarName ) ) { val arr = variableNameToArr . remove ( oldVarName ) ; variableNameToArr . put ( withName , arr ) ; } if ( variableNameToShape . containsKey ( oldVarName ) ) { val shape = variableNameToShape . remove ( oldVarName ) ; variableNameToShape . put ( withName , shape ) ; } if ( gradients . containsKey ( oldVarName ) ) { val grad = gradients . remove ( oldVarName ) ; gradients . put ( withName , grad ) ; } if ( forwardVarForGrad . containsKey ( oldVarName ) ) { val forwardGrad = forwardVarForGrad . remove ( oldVarName ) ; forwardVarForGrad . put ( withName , forwardGrad ) ; } if ( placeHolderMap . containsKey ( oldVarName ) ) { val placeholders = placeHolderMap . remove ( oldVarName ) ; placeHolderMap . put ( withName , placeholders ) ; } if ( functionsArgsFor . containsKey ( oldVarName ) ) { val funcs = functionsArgsFor . remove ( oldVarName ) ; for ( val func : funcs ) { if ( func instanceof BaseOp ) { BaseOp baseOp = ( BaseOp ) func ; if ( baseOp . getXVertexId ( ) != null && baseOp . getXVertexId ( ) . equals ( oldVarName ) ) { baseOp . setXVertexId ( withName ) ; } if ( baseOp . getYVertexId ( ) != null && baseOp . getYVertexId ( ) . equals ( oldVarName ) ) { baseOp . setYVertexId ( withName ) ; } if ( baseOp . getZVertexId ( ) != null && baseOp . getZVertexId ( ) . equals ( oldVarName ) ) { baseOp . setZVertexId ( withName ) ; } } } functionsArgsFor . put ( withName , funcs ) ; } if ( functionOutputFor . containsKey ( oldVarName ) ) { val funcs = functionOutputFor . remove ( oldVarName ) ; for ( val func : funcs ) { if ( func instanceof BaseOp ) { BaseOp baseOp = ( BaseOp ) func ; if ( baseOp . getXVertexId ( ) != null && baseOp . getXVertexId ( ) . equals ( oldVarName ) ) { baseOp . setXVertexId ( withName ) ; } if ( baseOp . getYVertexId ( ) != null && baseOp . getYVertexId ( ) . equals ( oldVarName ) ) { baseOp . setYVertexId ( withName ) ; } if ( baseOp . getZVertexId ( ) != null && baseOp . getZVertexId ( ) . equals ( oldVarName ) ) { baseOp . setZVertexId ( withName ) ; } } } functionOutputFor . put ( withName , funcs ) ; } variableMap . remove ( oldVarName ) ;


signature:
public class SameDiff { /** * Get the function by the { @ link DifferentialFunction # getOwnName ( ) }
 * @ param id the id of the function
 * @ return the function for the given id if it exists */
public DifferentialFunction getFunctionById ( String id ) { } }

implementation: if ( ! functionInstancesById . containsKey ( id ) ) { throw new ND4JIllegalStateException ( "No function with id " + id + " found!" ) ; } return functionInstancesById . get ( id ) ;


signature:
public class SameDiff { /** * Put the function for id
 * @ param id the id
 * @ param function the function */
public void putFunctionForId ( String id , DifferentialFunction function ) { } }

implementation: if ( functionInstancesById . containsKey ( id ) ) { throw new ND4JIllegalStateException ( "Function by id already exists!" ) ; } else if ( function instanceof SDVariable ) { throw new ND4JIllegalStateException ( "Function must not be a variable!" ) ; } functionInstancesById . put ( id , function ) ;


signature:
public class SameDiff { /** * Returns the inputs for the given function
 * @ param function the function to get the
 * inputs for
 * @ return the input ids for a given function */
public String [ ] getInputsForFunction ( DifferentialFunction function ) { } }

implementation: if ( ! incomingArgsReverse . containsKey ( function . getOwnName ( ) ) ) throw new ND4JIllegalStateException ( "Illegal function instance id found " + function . getOwnName ( ) ) ; return incomingArgsReverse . get ( function . getOwnName ( ) ) ;


signature:
public class SameDiff { /** * Update the ndarray for the given vertex id .
 * @ param varName
 * @ param arr
 * @ throws { @ link ND4JIllegalStateException } when the array does not exist . */
public void updateArrayForVarName ( String varName , INDArray arr ) { } }

implementation: if ( ! variableNameToArr . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( "Array for " + varName + " does not exist. Please use putArrayForVertexId instead." ) ; } variableNameToArr . put ( varName , arr ) ; reverseArrayLookup . put ( arr , getVariable ( varName ) ) ;


signature:
public class SameDiff { /** * Adds an ndarray for a given vertex id .
 * Use { @ link # updateArrayForVarName ( String , INDArray ) }
 * if the array already exists .
 * @ param varName the vertex id to add
 * @ param arr the array to add
 * @ throws { @ link ND4JIllegalStateException } when the array already exists . */
public void putArrayForVarName ( String varName , INDArray arr ) { } }

implementation: if ( varName == null ) throw new ND4JIllegalStateException ( "No null names allowed!" ) ; if ( variableNameToArr . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( "Array for " + varName + " already exists!" ) ; } variableNameToArr . put ( varName , arr ) ;


signature:
public class SameDiff { /** * Get the shape for the given vertex id .
 * Note that if an array is defined , it will use that shape instead .
 * A shape * and * an array should not be defined at the same time .
 * This wastes memory . The internal map used for tracking shapes for particular
 * vertex ids should also delete redundant shapes stored to avoid redundant sources of information .
 * @ param varName the vertex id to get the shape for
 * @ return the shape for the given vertex if if any . */
public long [ ] getShapeForVarName ( String varName ) { } }

implementation: if ( variableNameToArr . containsKey ( varName ) ) { return variableNameToArr . get ( varName ) . shape ( ) ; } return variableNameToShape . get ( varName ) ;


signature:
public class SameDiff { /** * Update a vertex id with the given shape .
 * Note that you should use { @ link # putShapeForVarName ( String , int [ ] ) }
 * if you want to add a new shape .
 * Update is meant to be an in place replacement
 * of the shape for the vertex id * only * .
 * @ param varName the vertex id to associate
 * @ param shape the shape to associate with */
public void updateShapeForVarName ( String varName , long [ ] shape ) { } }

implementation: if ( shape == null ) { throw new ND4JIllegalStateException ( "Null shapes not allowed!" ) ; } if ( variableNameToArr . containsKey ( varName ) && ! Arrays . equals ( variableNameToArr . get ( varName ) . shape ( ) , shape ) ) { throw new ND4JIllegalStateException ( "Already found an existing array!" ) ; } for ( int i = 0 ; i < shape . length ; i ++ ) { if ( shape [ i ] < 1 ) { addAsPlaceHolder ( varName ) ; placeHolderOriginalShapes . put ( varName , shape ) ; return ; } } variableNameToShape . put ( varName , shape ) ;


signature:
public class SameDiff { /** * Associate a vertex id with the given shape .
 * @ param varName the vertex id to associate
 * @ param shape the shape to associate with */
public void putShapeForVarName ( String varName , long [ ] shape ) { } }

implementation: if ( shape == null ) { throw new ND4JIllegalStateException ( "Shape must not be null!" ) ; } if ( variableNameToShape . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( "Shape for " + varName + " already exists!" ) ; } for ( int i = 0 ; i < shape . length ; i ++ ) { if ( shape [ i ] < 1 ) { addAsPlaceHolder ( varName ) ; placeHolderOriginalShapes . put ( varName , shape ) ; return ; } } variableNameToShape . put ( varName , shape ) ;