Input:
PLEASE NOTE : Specific implementation on systems without special devices can return HostPointer here [CODESPLIT] @ Override public org . bytedeco . javacpp . Pointer getDevicePointer ( DataBuffer buffer , CudaContext context ) { // TODO: It would be awesome to get rid of typecasting here //getCudaContext().syncOldStream(); AllocationPoint dstPoint = ( ( BaseCudaDataBuffer ) buffer ) . getAllocationPoint ( ) ; //log.info("getDevicePointer called"); /*
        if (configuration.getMemoryModel() == Configuration.MemoryModel.DELAYED && dstPoint.getAllocationStatus() == AllocationStatus.HOST) {

            // if we have constant buffer (aka shapeInfo or other constant stuff)
            if (buffer.isConstant()) {
                Nd4j.getConstantHandler().moveToConstantSpace(buffer);
            } else {
                PointersPair pair = memoryProvider.malloc(dstPoint.getShape(), dstPoint, AllocationStatus.DEVICE);

                if (pair != null) {
                    Integer deviceId = getDeviceId();

                    dstPoint.getPointers().setDevicePointer(pair.getDevicePointer());
                    dstPoint.setAllocationStatus(AllocationStatus.DEVICE);

                    deviceAllocations.get(deviceId).put(dstPoint.getObjectId(), dstPoint.getObjectId());

                    zeroAllocations.get(dstPoint.getBucketId()).remove(dstPoint.getObjectId());
                    deviceMemoryTracker.addToAllocation(Thread.currentThread().getId(), deviceId, AllocationUtils.getRequiredMemory(dstPoint.getShape()));

                    dstPoint.tickHostWrite();
                }
            }
        }
        */ // here's the place, where we do care about promotion. but we only care about promotion of original  buffers if ( dstPoint . getAllocationStatus ( ) == AllocationStatus . HOST && buffer . offset ( ) == 0 && 1 < 0 ) { if ( dstPoint . getDeviceTicks ( ) > configuration . getMinimumRelocationThreshold ( ) ) { // at this point we know, that this request is done withing some existent context long requiredMemory = AllocationUtils . getRequiredMemory ( dstPoint . getShape ( ) ) ; if ( deviceMemoryTracker . reserveAllocationIfPossible ( Thread . currentThread ( ) . getId ( ) , getDeviceId ( ) , requiredMemory ) && pingDeviceForFreeMemory ( getDeviceId ( ) , requiredMemory ) ) { // so, memory is reserved promoteObject ( buffer ) ; } } } // if that's device state, we probably might want to update device memory state if ( dstPoint . getAllocationStatus ( ) == AllocationStatus . DEVICE ) { if ( ! dstPoint . isActualOnDeviceSide ( ) ) { //                log.info("Relocating to GPU"); relocate ( AllocationStatus . HOST , AllocationStatus . DEVICE , dstPoint , dstPoint . getShape ( ) , context ) ; } else { //  log.info("Buffer is actual on device side: " + dstPoint.getShape()); } } //else log.info("Not on [DEVICE]"); //  we update memory use counter, to announce that it's somehow used on device dstPoint . tickDeviceRead ( ) ; // return pointer with offset if needed. length is specified for constructor compatibility purposes CudaPointer p = new CudaPointer ( dstPoint . getPointers ( ) . getDevicePointer ( ) , buffer . length ( ) , ( buffer . offset ( ) * buffer . getElementSize ( ) ) ) ; switch ( buffer . dataType ( ) ) { case DOUBLE : return p . asDoublePointer ( ) ; case FLOAT : return p . asFloatPointer ( ) ; case INT : return p . asIntPointer ( ) ; case HALF : return p . asShortPointer ( ) ; case LONG : return p . asLongPointer ( ) ; default : return p ; } }


Input: Returns requested ClassPathResource as InputStream object [CODESPLIT] public InputStream getInputStream ( ) throws FileNotFoundException { URL url = this . getUrl ( ) ; if ( isJarURL ( url ) ) { try { url = extractActualUrl ( url ) ; ZipFile zipFile = new ZipFile ( url . getFile ( ) ) ; ZipEntry entry = zipFile . getEntry ( this . resourceName ) ; InputStream stream = zipFile . getInputStream ( entry ) ; return stream ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { File srcFile = this . getFile ( ) ; return new FileInputStream ( srcFile ) ; } }


Input:
This method returns deviceId for given thread identified by threadId [CODESPLIT] @ Override public Integer getDeviceForThread ( long threadId ) { if ( getNumberOfDevices ( ) == 1 ) return 0 ; Integer aff = affinityMap . get ( threadId ) ; if ( aff == null ) { Integer deviceId = getNextDevice ( threadId ) ; affinityMap . put ( threadId , deviceId ) ; affiliated . set ( new AtomicBoolean ( false ) ) ; if ( threadId == Thread . currentThread ( ) . getId ( ) ) { NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . setDevice ( new CudaPointer ( deviceId ) ) ; //logger.error("setDevice({}) called for thread {}", deviceId, Thread.currentThread().getName()); affiliated . get ( ) . set ( true ) ; } return deviceId ; } else { if ( threadId == Thread . currentThread ( ) . getId ( ) ) { if ( affiliated . get ( ) == null ) affiliated . set ( new AtomicBoolean ( false ) ) ; if ( ! affiliated . get ( ) . get ( ) ) { NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . setDevice ( new CudaPointer ( aff ) ) ; //logger.error("SCARY setDevice({}) called for thread {}", aff, threadId); affiliated . get ( ) . set ( true ) ; return aff ; } } return aff ; } /*

        return affinityMap.get(threadId);
*/ //return 0; }


Input: This method pairs specified thread & device [CODESPLIT] @ Override public void attachThreadToDevice ( long threadId , Integer deviceId ) { List < Integer > devices = new ArrayList <> ( CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) ) ; logger . debug ( "Manually mapping thread [{}] to device [{}], out of [{}] devices..." , threadId , deviceId , devices . size ( ) ) ; affinityMap . put ( threadId , deviceId ) ; }


Input: This method returns device id available . Round - robin balancing used here . [CODESPLIT] protected Integer getNextDevice ( long threadId ) { Integer device = null ; if ( ! CudaEnvironment . getInstance ( ) . getConfiguration ( ) . isForcedSingleGPU ( ) && getNumberOfDevices ( ) > 0 ) { // simple round-robin here synchronized ( this ) { device = CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . get ( devPtr . getAndIncrement ( ) ) ; // We check only for number of entries here, not their actual values if ( devPtr . get ( ) >= CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . size ( ) ) devPtr . set ( 0 ) ; logger . debug ( "Mapping thread [{}] to device [{}], out of [{}] devices..." , threadId , device , CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . size ( ) ) ; } } else { device = CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . get ( 0 ) ; logger . debug ( "Single device is forced, mapping to device [{}]" , device ) ; } return device ; }


Input: Loads the specified library . The full name of the library is created by calling { @link LibUtils#createLibName ( String ) } with the given argument . The method will attempt to load the library as a as a resource ( for usage within a JAR ) and if this fails using the usual System . loadLibrary call . [CODESPLIT] public static void loadLibrary ( String baseName ) { String libName = LibUtils . createLibName ( baseName ) ; Throwable throwable = null ; try { loadLibraryResource ( libName ) ; return ; } catch ( Throwable t ) { throwable = t ; } try { System . loadLibrary ( libName ) ; return ; } catch ( Throwable t ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; pw . println ( "Error while loading native library \"" + libName + "\" with base name \"" + baseName + "\"" ) ; pw . println ( "Operating system name: " + System . getProperty ( "os.name" ) ) ; pw . println ( "Architecture         : " + System . getProperty ( "os.arch" ) ) ; pw . println ( "Architecture bit size: " + System . getProperty ( "sun.arch.data.model" ) ) ; if ( throwable != null ) { pw . println ( "Stack trace from the attempt to " + "load the library as a resource:" ) ; throwable . printStackTrace ( pw ) ; } pw . println ( "Stack trace from the attempt to " + "load the library as a file:" ) ; t . printStackTrace ( pw ) ; pw . flush ( ) ; pw . close ( ) ; throw new UnsatisfiedLinkError ( "Could not load the native library.\n" + sw . toString ( ) ) ; } }


Input: Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadTempBinaryFile ( String libName ) throws Exception { String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; String fullName = libPrefix + libName ; String resourceName = fullName + "." + libExtension ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( "No resource found with name '" + resourceName + "'" ) ; } File tempFile = new File ( System . getProperty ( "java.io.tmpdir" ) , fullName + "." + libExtension ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . getAbsolutePath ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }


Input: Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadTempBinaryFile ( Class < ? > libName ) throws Exception { String os = getOsName ( ) ; String arch = getArchName ( ) ; String resourceFolder = os + "-" + arch ; String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; StringBuilder sb = new StringBuilder ( ) . append ( libName . getPackage ( ) . getName ( ) . replace ( "." , "/" ) + "/" ) . append ( resourceFolder ) . append ( "/" ) . append ( libPrefix ) . append ( "jni" + libName . getSimpleName ( ) + "." ) . append ( libExtension ) ; String resourceName = sb . toString ( ) ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( "No resource found with name '" + resourceName + "'" ) ; } String fullName = libPrefix + "jni" + libName . getSimpleName ( ) + "." + libExtension ; File tempFile = new File ( System . getProperty ( "java.io.tmpdir" ) , fullName ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . getAbsolutePath ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }


Input: Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadJavaCppResource ( String libName ) throws Throwable { String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; String fullName = libPrefix + libName ; String resourceName = fullName + "." + libExtension ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( "No resource found with name '" + resourceName + "'" ) ; } File tempFile = File . createTempFile ( fullName , "." + libExtension ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . toString ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }


Input: Get the name of the os for libary discovery on the classpath [CODESPLIT] public static String getOsName ( ) { OSType osType = calculateOS ( ) ; switch ( osType ) { case APPLE : return "macosx" ; case LINUX : return "linux" ; case SUN : return "sun" ; case WINDOWS : return "windows" ; } return "" ; }


Input: Creates the name for the native library with the given base name for the current operating system and architecture . The resulting name will be of the form<br / > baseName - OSType - ARCHType<br / > where OSType and ARCHType are the <strong > lower case< / strong > Strings of the respective enum constants . Example : <br / > jcuda - windows - x86<br / > [CODESPLIT] public static String createLibName ( String baseName ) { OSType osType = calculateOS ( ) ; ARCHType archType = calculateArch ( ) ; String libName = baseName ; libName += "-" + osType . toString ( ) . toLowerCase ( Locale . ENGLISH ) ; libName += "-" + archType . toString ( ) . toLowerCase ( Locale . ENGLISH ) ; return libName ; }


Input: Calculates the current ARCHType [CODESPLIT] public static ARCHType calculateArch ( ) { 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 ; }


Input: Publish to a kafka topic based on the connection information [CODESPLIT] public void publish ( INDArray arr ) { if ( producerTemplate == null ) producerTemplate = camelContext . createProducerTemplate ( ) ; producerTemplate . sendBody ( "direct:start" , arr ) ; }


Input: Start the server [CODESPLIT] public void start ( ) { 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 ) ; } }


Input: Create a data buffer based on the given pointer data buffer opType and length of the buffer [CODESPLIT] @ Override public DataBuffer create ( Pointer pointer , DataBuffer . Type type , long length , Indexer indexer ) { 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 ) ; }


Input: This method checks if any Op operand has data opType of INT and throws exception if any . [CODESPLIT] protected void interceptIntDataType ( Op op ) { // 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." ) ; }


Input: Add two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber addi ( IComplexNumber c , IComplexNumber result ) { return result . set ( result . realComponent ( ) . floatValue ( ) + c . realComponent ( ) . floatValue ( ) , result . imaginaryComponent ( ) . floatValue ( ) + c . imaginaryComponent ( ) . floatValue ( ) ) ; }


Input: Multiply two complex numbers inplace [CODESPLIT] @ Override public IComplexNumber muli ( IComplexNumber c , IComplexNumber result ) { 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 ) ; }


Input: Divide two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber divi ( IComplexNumber c , IComplexNumber result ) { 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 ) ; }


Input: Drop - in replacement wrapper for BaseDataBuffer . read () method aware of CompressedDataBuffer [CODESPLIT] public static DataBuffer readUnknown ( DataInputStream s , long length ) { 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 ) ; } } }


Input: This method assigns specific value to either specific row or whole array . Array is identified by key [CODESPLIT] @ Override public void processMessage ( ) { 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 ) ; } }


Input: Local response normalization operation . [CODESPLIT] public SDVariable localResponseNormalization ( SDVariable inputs , LocalResponseNormalizationConfig lrnConfig ) { LocalResponseNormalization lrn = LocalResponseNormalization . builder ( ) . inputFunctions ( new SDVariable [ ] { inputs } ) . sameDiff ( sameDiff ( ) ) . config ( lrnConfig ) . build ( ) ; return lrn . outputVariables ( ) [ 0 ] ; }


Input: Conv1d operation . [CODESPLIT] public SDVariable conv1d ( SDVariable [ ] inputs , Conv1DConfig conv1DConfig ) { Conv1D conv1D = Conv1D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv1DConfig ) . build ( ) ; return conv1D . outputVariables ( ) [ 0 ] ; }


Input: Conv2d operation . [CODESPLIT] public SDVariable conv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { Conv2D conv2D = Conv2D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv2DConfig ) . build ( ) ; return conv2D . outputVariables ( ) [ 0 ] ; }


Input: Average pooling 2d operation . [CODESPLIT] public SDVariable avgPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { AvgPooling2D avgPooling2D = AvgPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return avgPooling2D . outputVariables ( ) [ 0 ] ; }


Input: Max pooling 2d operation . [CODESPLIT] public SDVariable maxPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { MaxPooling2D maxPooling2D = MaxPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return maxPooling2D . outputVariables ( ) [ 0 ] ; }


Input: Avg pooling 3d operation . [CODESPLIT] public SDVariable avgPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . AVG ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ; }


Input: Max pooling 3d operation . [CODESPLIT] public SDVariable maxPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . MAX ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ; }


Input: Separable Conv2d operation . [CODESPLIT] public SDVariable sconv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { SConv2D sconv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( conv2DConfig ) . build ( ) ; return sconv2D . outputVariables ( ) [ 0 ] ; }


Input: Depthwise Conv2d operation . This is just separable convolution with only the depth - wise weights specified . [CODESPLIT] public SDVariable depthWiseConv2d ( SDVariable [ ] inputs , Conv2DConfig depthConv2DConfig ) { SConv2D depthWiseConv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( depthConv2DConfig ) . build ( ) ; return depthWiseConv2D . outputVariables ( ) [ 0 ] ; }


Input: Deconv2d operation . [CODESPLIT] public SDVariable deconv2d ( SDVariable [ ] inputs , DeConv2DConfig deconv2DConfig ) { DeConv2D deconv2D = DeConv2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( deconv2DConfig ) . build ( ) ; return deconv2D . outputVariables ( ) [ 0 ] ; }


Input: 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 [CODESPLIT] public static INDArray [ ] covarianceMatrix ( INDArray in ) { 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 } ; }


Input: 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 ] . [CODESPLIT] public static INDArray [ ] principalComponents ( INDArray cov ) { 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 ; }


Input: This method resets all counters [CODESPLIT] public void reset ( ) { 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 ( ) ; }


Input: This method returns op class opName [CODESPLIT] protected String getOpClass ( Op op ) { 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" ; }


Input: Create a complex ndarray from the passed in indarray [CODESPLIT] @ Override public IComplexNDArray createComplex ( List < IComplexNDArray > arrs , int [ ] shape ) { return new ComplexNDArray ( arrs , shape ) ; }


Input: Allocate and return a new array based on the vertex id and weight initialization . [CODESPLIT] public INDArray storeAndAllocateNewArray ( ) { 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 ; }


Input: A getter for the allocated ndarray with this { @link SDVariable } . [CODESPLIT] public INDArray getArr ( ) { 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 ( ) ) ; }


Input: Returns the shape of this variable [CODESPLIT] public long [ ] getShape ( ) { long [ ] initialShape = sameDiff . getShapeForVarName ( getVarName ( ) ) ; if ( initialShape == null ) { val arr = getArr ( ) ; if ( arr != null ) return arr . shape ( ) ; } return initialShape ; }


Input: Evaluate the result of this variable [CODESPLIT] public INDArray eval ( ) { 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 ( ) ; }


Input: This method creates compressed INDArray from Java double array skipping usual INDArray instantiation routines [CODESPLIT] @ Override public INDArray compress ( double [ ] data , int [ ] shape , char order ) { 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 ) ; }


Input: Returns the exponential of a complex ndarray [CODESPLIT] public static IComplexNDArray expi ( IComplexNDArray toExp ) { 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 ( ) ) ; }


Input: Center an array [CODESPLIT] public static IComplexNDArray center ( IComplexNDArray arr , long [ ] shape ) { 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 ; } }


Input: Truncates an ndarray to the specified shape . If the shape is the same or greater it just returns the original array [CODESPLIT] public static IComplexNDArray truncate ( IComplexNDArray nd , int n , int dimension ) { 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 ; }


Input: Pads an ndarray with zeros [CODESPLIT] public static IComplexNDArray padWithZeros ( IComplexNDArray nd , long [ ] targetShape ) { 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 ; }


Input: Find the index of the element with maximum absolute value [CODESPLIT] @ Override public int iamax ( INDArray arr ) { 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 ( ) ; }


Input: This method duplicates array and stores it to all devices [CODESPLIT] public void broadcast ( INDArray array ) { 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 ) ) ; } } }


Input: This method will be started in context of executor either Shard Client or Backup node [CODESPLIT] @ Override public void processMessage ( ) { VectorAggregation aggregation = new VectorAggregation ( rowIndex , ( short ) voidConfiguration . getNumberOfShards ( ) , shardIndex , storage . getArray ( key ) . getRow ( rowIndex ) . dup ( ) ) ; aggregation . setOriginatorId ( this . getOriginatorId ( ) ) ; transport . sendMessage ( aggregation ) ; }


Input:
Euler’s constant . [CODESPLIT] static public BigDecimal pi ( final MathContext mc ) { /* 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 ) ; } }


Input:
Euler - Mascheroni constant . [CODESPLIT] static public BigDecimal gamma ( MathContext mc ) { /* 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 ) ; } }


Input: The square root . [CODESPLIT] static public BigDecimal sqrt ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( "negative argument " + x . toString ( ) + " of square root" ) ; } return root ( 2 , x ) ; }


Input: The cube root . [CODESPLIT] static public BigDecimal cbrt ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return root ( 3 , x . negate ( ) ) . negate ( ) ; } else { return root ( 3 , x ) ; } }


Input:
The integer root . [CODESPLIT] static public BigDecimal root ( final int n , final BigDecimal x ) { 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 ) ) ) ; }


Input:
The hypotenuse . [CODESPLIT] static public BigDecimal hypot ( final BigDecimal x , final BigDecimal y ) { /* 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 ) ; }


Input:
The hypotenuse . [CODESPLIT] static public BigDecimal hypot ( final int n , final BigDecimal x ) { /* 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 ) ; }


Input:
The exponential function . [CODESPLIT] static public BigDecimal exp ( BigDecimal x ) { /* 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 ) ; } } }


Input:
The base of the natural logarithm . [CODESPLIT] static public BigDecimal exp ( final MathContext mc ) { /* 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 ) ; } }


Input:
The natural logarithm . [CODESPLIT] static public BigDecimal log ( BigDecimal x ) { /* 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 ) ; } }


Input:
The natural logarithm . [CODESPLIT] static public BigDecimal log ( int n , final MathContext mc ) { /* 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 ) ; } }


Input:
The natural logarithm . [CODESPLIT] static public BigDecimal log ( final Rational r , final MathContext mc ) { /* 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 ) ; } }


Input:
Power function . [CODESPLIT] static public BigDecimal pow ( final BigDecimal x , final BigDecimal y ) { 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 ) ; } }


Input:
Raise to an integer power and round . [CODESPLIT] static public BigDecimal powRound ( final BigDecimal x , final int n ) { /* 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 ) ; }


Input:
Trigonometric sine . [CODESPLIT] static public BigDecimal sin ( final BigDecimal x ) { 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 */ }


Input:
The trigonometric tangent . [CODESPLIT] static public BigDecimal tan ( final BigDecimal x ) { 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 ) ; } } }


Input:
The inverse trigonometric sine . [CODESPLIT] static public BigDecimal asin ( final BigDecimal x ) { 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 ) ; } }


Input:
The inverse trigonometric tangent . [CODESPLIT] static public BigDecimal atan ( final BigDecimal x ) { 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 ) ; } }


Input:
The hyperbolic cosine . [CODESPLIT] static public BigDecimal cosh ( final BigDecimal x ) { 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 ) ; } } }


Input:
The hyperbolic sine . [CODESPLIT] static public BigDecimal sinh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return sinh ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { if ( x . doubleValue ( ) > 2.4 ) { /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
                 */ BigDecimal two = new BigDecimal ( 2 ) ; BigDecimal xhalf = x . divide ( two ) ; BigDecimal resul = sinh ( xhalf ) . multiply ( cosh ( xhalf ) ) . multiply ( two ) ; /* The error in the result is set by the error in x itself.
                 * The first derivative of sinh(x) is cosh(x), so the absolute error
                 * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
                 */ double eps = Math . tanh ( x . doubleValue ( ) ) ; MathContext mc = new MathContext ( err2prec ( 0.5 * x . ulp ( ) . doubleValue ( ) / eps ) ) ; return resul . round ( mc ) ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */ BigDecimal resul = xhighpr ; /* x^i */ BigDecimal xpowi = xhighpr ; /* 2i+1 factorial */ BigInteger ifac = BigInteger . ONE ; /* The error in the result is set by the error in x itself.
                 */ double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; /* The error in the result is set by the error in x itself.
                 * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
                 * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
                 * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
                 */ int k = ( int ) ( x . precision ( ) / Math . log10 ( 1.0 / xhighpr . doubleValue ( ) ) ) / 2 ; MathContext mcTay = new MathContext ( err2prec ( x . doubleValue ( ) , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD: at which precision will 2*i or 2*i+1 overflow?
                     */ ifac = ifac . multiply ( 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 ) ; } } }


Input:
The hyperbolic tangent . [CODESPLIT] static public BigDecimal tanh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return tanh ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .
             */ BigDecimal exp2x = exp ( xhighpr . multiply ( new BigDecimal ( - 2 ) ) ) ; /* The error in tanh x is err(x)/cosh^2(x).
             */ double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . pow ( Math . cosh ( x . doubleValue ( ) ) , 2.0 ) ; MathContext mc = new MathContext ( err2prec ( Math . tanh ( x . doubleValue ( ) ) , eps ) ) ; return BigDecimal . ONE . subtract ( exp2x ) . divide ( BigDecimal . ONE . add ( exp2x ) , mc ) ; } }


Input:
The inverse hyperbolic sine . [CODESPLIT] static public BigDecimal asinh ( final BigDecimal x ) { 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 ) ; } }


Input:
The inverse hyperbolic cosine . [CODESPLIT] static public BigDecimal acosh ( final BigDecimal x ) { 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 ) ; } }


Input:
The Gamma function . [CODESPLIT] static public BigDecimal Gamma ( final BigDecimal x ) { /* 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 ) ; } }


Input:
Pochhammer’s function . [CODESPLIT] static public BigDecimal pochhammer ( final BigDecimal x , final int n ) { /* 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 ) ) ) ; } }


Input:
Reduce value to the interval [ 0 2 * Pi ] . [CODESPLIT] static public BigDecimal mod2pi ( BigDecimal x ) { /* 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 ) ; }


Input:
Reduce value to the interval [ - Pi / 2 Pi / 2 ] . [CODESPLIT] static public BigDecimal modpi ( BigDecimal x ) { /* 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 ) ; }


Input:
Riemann zeta function . [CODESPLIT] static public BigDecimal zeta ( final int n , final MathContext mc ) { 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 ) ; } }


Input:
Riemann zeta function . [CODESPLIT] static public double zeta1 ( final int n ) { /* precomputed static table in double precision
         */ final double [ ] zmin1 = { 0. , 0. , 6.449340668482264364724151666e-01 , 2.020569031595942853997381615e-01 , 8.232323371113819151600369654e-02 , 3.692775514336992633136548646e-02 , 1.734306198444913971451792979e-02 , 8.349277381922826839797549850e-03 , 4.077356197944339378685238509e-03 , 2.008392826082214417852769232e-03 , 9.945751278180853371459589003e-04 , 4.941886041194645587022825265e-04 , 2.460865533080482986379980477e-04 , 1.227133475784891467518365264e-04 , 6.124813505870482925854510514e-05 , 3.058823630702049355172851064e-05 , 1.528225940865187173257148764e-05 , 7.637197637899762273600293563e-06 , 3.817293264999839856461644622e-06 , 1.908212716553938925656957795e-06 , 9.539620338727961131520386834e-07 , 4.769329867878064631167196044e-07 , 2.384505027277329900036481868e-07 , 1.192199259653110730677887189e-07 , 5.960818905125947961244020794e-08 , 2.980350351465228018606370507e-08 , 1.490155482836504123465850663e-08 , 7.450711789835429491981004171e-09 , 3.725334024788457054819204018e-09 , 1.862659723513049006403909945e-09 , 9.313274324196681828717647350e-10 , 4.656629065033784072989233251e-10 , 2.328311833676505492001455976e-10 , 1.164155017270051977592973835e-10 , 5.820772087902700889243685989e-11 , 2.910385044497099686929425228e-11 , 1.455192189104198423592963225e-11 , 7.275959835057481014520869012e-12 , 3.637979547378651190237236356e-12 , 1.818989650307065947584832101e-12 , 9.094947840263889282533118387e-13 , 4.547473783042154026799112029e-13 , 2.273736845824652515226821578e-13 , 1.136868407680227849349104838e-13 , 5.684341987627585609277182968e-14 , 2.842170976889301855455073705e-14 , 1.421085482803160676983430714e-14 , 7.105427395210852712877354480e-15 , 3.552713691337113673298469534e-15 , 1.776356843579120327473349014e-15 , 8.881784210930815903096091386e-16 , 4.440892103143813364197770940e-16 , 2.220446050798041983999320094e-16 , 1.110223025141066133720544570e-16 , 5.551115124845481243723736590e-17 , 2.775557562136124172581632454e-17 , 1.387778780972523276283909491e-17 , 6.938893904544153697446085326e-18 , 3.469446952165922624744271496e-18 , 1.734723476047576572048972970e-18 , 8.673617380119933728342055067e-19 , 4.336808690020650487497023566e-19 , 2.168404344997219785013910168e-19 , 1.084202172494241406301271117e-19 , 5.421010862456645410918700404e-20 , 2.710505431223468831954621312e-20 , 1.355252715610116458148523400e-20 , 6.776263578045189097995298742e-21 , 3.388131789020796818085703100e-21 , 1.694065894509799165406492747e-21 , 8.470329472546998348246992609e-22 , 4.235164736272833347862270483e-22 , 2.117582368136194731844209440e-22 , 1.058791184068023385226500154e-22 , 5.293955920339870323813912303e-23 , 2.646977960169852961134116684e-23 , 1.323488980084899080309451025e-23 , 6.617444900424404067355245332e-24 , 3.308722450212171588946956384e-24 , 1.654361225106075646229923677e-24 , 8.271806125530344403671105617e-25 , 4.135903062765160926009382456e-25 , 2.067951531382576704395967919e-25 , 1.033975765691287099328409559e-25 , 5.169878828456431320410133217e-26 , 2.584939414228214268127761771e-26 , 1.292469707114106670038112612e-26 , 6.462348535570531803438002161e-27 , 3.231174267785265386134814118e-27 , 1.615587133892632521206011406e-27 , 8.077935669463162033158738186e-28 , 4.038967834731580825622262813e-28 , 2.019483917365790349158762647e-28 , 1.009741958682895153361925070e-28 , 5.048709793414475696084771173e-29 , 2.524354896707237824467434194e-29 , 1.262177448353618904375399966e-29 , 6.310887241768094495682609390e-30 , 3.155443620884047239109841220e-30 , 1.577721810442023616644432780e-30 , 7.888609052210118073520537800e-31 } ; if ( n <= 0 ) { throw new ProviderException ( "Unimplemented zeta at negative argument " + n ) ; } if ( n == 1 ) { throw new ArithmeticException ( "Pole at zeta(1) " ) ; } if ( n < zmin1 . length ) /* look it up if available */ { return zmin1 [ n ] ; } else { /* Result is roughly 2^(-n), desired accuracy 18 digits. If zeta(n) is computed, the equivalent accuracy
             * in relative units is higher, because zeta is around 1.
             */ double eps = 1.e-18 * Math . pow ( 2. , ( double ) ( - n ) ) ; MathContext mc = new MathContext ( err2prec ( eps ) ) ; return zeta ( n , mc ) . subtract ( BigDecimal . ONE ) . doubleValue ( ) ; } }


Input:
Broadhurst ladder sequence . [CODESPLIT] static protected BigDecimal broadhurstBBP ( final int n , final int p , final int a [ ] , MathContext mc ) { /* 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 ) ; }


Input:
Add and round according to the larger of the two ulp’s . [CODESPLIT] static public BigDecimal addRound ( final BigDecimal x , final BigDecimal y ) { 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 ) ; }


Input:
Subtract and round according to the larger of the two ulp’s . [CODESPLIT] static public BigDecimal subtractRound ( final BigDecimal x , final BigDecimal y ) { 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 ) ; }


Input:
Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final BigDecimal y ) { 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 ) ; }


Input:
Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final Rational f ) { 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 ) ; } }


Input:
Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final int n ) { 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 ) ; }


Input:
Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final BigInteger n ) { 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 ) ; }


Input:
Divide and round . [CODESPLIT] static public BigDecimal divideRound ( final BigDecimal x , final BigDecimal y ) { /* 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 ) ; }


Input:
Divide and round . [CODESPLIT] static public BigDecimal divideRound ( final int n , final BigDecimal x ) { /* 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 ) ; }


Input: Append decimal zeros to the value . This returns a value which appears to have a higher precision than the input . [CODESPLIT] static public BigDecimal scalePrec ( final BigDecimal x , int d ) { return x . setScale ( d + x . scale ( ) ) ; }


Input: Boost the precision by appending decimal zeros to the value . This returns a value which appears to have a higher precision than the input . [CODESPLIT] static public BigDecimal scalePrec ( final BigDecimal x , final MathContext mc ) { final int diffPr = mc . getPrecision ( ) - x . precision ( ) ; if ( diffPr > 0 ) { return scalePrec ( x , diffPr ) ; } else { return x ; } }


Input: Convert an absolute error to a precision . [CODESPLIT] static public int err2prec ( BigDecimal x , BigDecimal xerr ) { return err2prec ( xerr . divide ( x , MathContext . DECIMAL64 ) . doubleValue ( ) ) ; }